High java concurrent programming --04 - Hook thread and capture thread execution exception

1. Obtain abnormal thread running
abnormal processing of four API Thread class runtime:
public void setUncaughtExceptionHandler (UncaughtExceptionHandler EH): is a thread UncaughtExceptionHandler
public static setDefaultUncaughtExceptionHandler (UncaughtExceptionHandler EH): Set the global UncaughtExceptionHandler
public UncaughtExceptionHandler getUncaughtExceptionHandler (): Gets a specific UncaughtExceptionHandler thread
public static UncaughtExceptionHandler getDefaultUncaughtExceptionHandler (): Gets global UncaughtExcepitonHandler

1.UncaughtExceptionHandler Introduction
thread execution units are not allowed to throw checked exceptions, the thread runs in its own context, derives its thread can not get the information directly to the abnormal it runs, which, java provides a UncaughtExceptionHandler interface when the thread during operation it will be called when an exception occurs UncaughtExceptionHandler interfaces, so that the thread errors at run time and what kind of error.
Thread class is the interface UncaughtExceptionHandler an internal interface:

@FunctionalInterface
public interface UncaughtExceptionHandler {
    /**
     * Method invoked when the given thread terminates due to the
     * given uncaught exception.
     * <p>Any exception thrown by this method will be ignored by the
     * Java Virtual Machine.
     * @param t the thread
     * @param e the exception
     */
    void uncaughtException(Thread t, Throwable e);
}

The interface is a function interface, only one way, will be called the Thread class dispatchUncaughtException method:

/**
 * Dispatch an uncaught exception to the handler. This method is
 * intended to be called only by the JVM.
 */
private void dispatchUncaughtException(Throwable e) {
    getUncaughtExceptionHandler().uncaughtException(this, e);
}

When an exception occurs the thread, it calls dispatchUncaughtException method callback interface thread instance and abnormality information is transmitted to a corresponding
use of the following sample code:

public  class UncaughtExceptionHandlerTest {
     public  static  void main (String [] args) {
         // set the callback interface 
        Thread.setDefaultUncaughtExceptionHandler ((T, E) -> { 
            System.out.println ( "---> Thread" + t.getName () + "abnormality occurs, the abnormality information is as follows:" ); 
            e.printStackTrace (); 
        }); 
        new new the Thread (() -> {
             the try { 
                TimeUnit.SECONDS.sleep ( 2 ); 
            } the catch (InterruptedException E1) { 
                E1 .printStackTrace (); 
            } 
            //Here throws unchecked exception 
            System.out.println (the 2/0 ); 
        }) Start ();. 
    } 
}

Output:

---> Thread the Thread- 0 exception occurs, the exception information is as follows: 
java.lang.ArithmeticException: / by ZERO 
    AT cp7.cp1.UncaughtExceptionHandlerTest.lambda $ 1 (UncaughtExceptionHandlerTest.java:19 ) 
    AT java.base /java.lang. Thread.run (Thread.java:834)

2.Hook thread
2.1Hook thread introduction
injected into the program a Hook thread jvm, jvm when the program exits, Hook thread starts execution, can inject multiple threads to Hook jvm program by Runtime:

public class HookTest {
    public static void main(String[] args) {
        //注入5个Hook线程
        for(int i = 0;i < 5;i ++) {
            int x = i;
            Runtime.getRuntime().addShutdownHook(new Thread(()->{
                System.out.println("hook" + x + " run");
                try {
                    TimeUnit.SECONDS.sleep(2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("hook" + x + " is over");
            }));
        }
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("main is over");
    }
}


Output:
main IS over
HOOK2 RUN
hook1 RUN
hook0 RUN
hook4 RUN
hook3 RUN
hook1 IS over
hook4 IS over
hook0 IS over
hook3 IS over
HOOK2 IS over
2.2Hook threads and precautions
Hook thread can prevent the repeated start the program, start the process before you can create a look file, create a file to determine the release existed and, if it is deemed to have been started by the characteristics of Hook thread delete this file when the program ends. Such as MySQL, zookeeper, kafka software can see the presence of lock files
Note:
1) Hook thread is performed only when the exit signal is received, if the kill -9 command to end the process, Hook thread does not perform, will not lock file be cleaned
2) Hook thread can release some resources to do the work, such as closing a file handle, socket link, database connection, etc.
3) try not to perform some very long time-consuming operation in Hook thread, otherwise they could not quit the program

Guess you like

Origin www.cnblogs.com/ShouWangYiXin/p/11449594.html
Recommended