Abnormal captured in multithreading

Introduction: Today is the first day of the official start of the problem encountered exception caught under the circumstances at the time of writing multi-threaded code, and therefore wanted to record solutions

method 1

The easiest way to violence, can be directly trycatch in sub-method

PlatformThreadPool.getInstance().execute(() -> {
                try {
                   有问题的方法
                }catch (Exception e){
                    log.info(e.getLocalizedMessage());
                }
            });

Method 2

Set exception handler thread. Specifically the following can be:
(. 1) is provided Thread.setUncaughtExceptionHandler the exception handler of the current thread;
(2) sets the default Thread.setDefaultUncaughtExceptionHandler exception handler for the entire program;
if the current thread has exception handlers (not the default), takes precedence UncaughtExceptionHandler class; otherwise, if the thread group of the current thread belongs abnormal processor, the thread group is used
UncaughtExceptionHandler; otherwise, use the global default DefaultUncaughtExceptionHandler; if not, then the child thread exits.
Note : abnormality has occurred in the sub-thread, if there is no deal to take over the class, then, it is a direct exit without recording any log.
So, if nothing is done, there will be neither a sub-thread tasks execute successfully, nor any "strange" phenomenon prompted the log.

public class ChildThread implements Runnable {    
    private static ChildThreadExceptionHandler exceptionHandler;

    static {
        exceptionHandler = new ChildThreadExceptionHandler();
    }

    public void run() {
        Thread.currentThread().setUncaughtExceptionHandler(exceptionHandler);
        System.out.println("do something 1");
        exceptionMethod();
        System.out.println("do something 2");
    }

    public static class ChildThreadExceptionHandler implements Thread.UncaughtExceptionHandler {
        public void uncaughtException(Thread t, Throwable e) {
            System.out.println(String.format("handle exception in child thread. %s", e));
        }
    }
}

Or, set the default exception handler for all threads

public class ChildThread implements Runnable {
    private static ChildThreadExceptionHandler exceptionHandler;

    static {
        exceptionHandler = new ChildThreadExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(exceptionHandler);
    }

    public void run() {
        System.out.println("do something 1");
        exceptionMethod();
        System.out.println("do something 2");
    }

    private void exceptionMethod() {
        throw new RuntimeException("ChildThread exception");
    }

    public static class ChildThreadExceptionHandler implements Thread.UncaughtExceptionHandler {
        public void uncaughtException(Thread t, Throwable e) {
            System.out.println(String.format("handle exception in child thread. %s", e));
        }
    }
}

Method 3

Future's get method captured by abnormal
submit a method to be able to get return information using a thread pool, which is ExecutorService.submit (Callable)
can get a Future object thread execution results after submit, and if an exception occurs in the child thread, getting the return value future.get (), you can capture
ExecutionException abnormal, so they know an abnormality has occurred in the sub-thread.
Child thread demo

public class ChildThread implements Callable<String> {
    public String call() throws Exception {
        System.out.println("do something 1");
        exceptionMethod();
        System.out.println("do something 2");
        return "test result";
    }

    private void exceptionMethod() {
        throw new RuntimeException("ChildThread1 exception");
    }
}

The main thread demo

public class Main {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(8);
        Future future = executorService.submit(new ChildThread());
        try {
            future.get();
        } catch (InterruptedException | ExecutionException e) {
            System.out.println(String.format("handle exception in child thread. %s", e));
        } finally {
            executorService.shutdown();
        }
    }
}

命令行输出:
do something 1
handle exception in child thread. java.util.concurrent.ExecutionException: java.lang.RuntimeException: ChildThread1 exception

Published 25 original articles · won praise 22 · views 3633

Guess you like

Origin blog.csdn.net/weixin_42443419/article/details/104248778