简体   繁体   中英

Catch exception for Executor, thread pool

For one thread, I catch the uncaught exception via below code segments. However, for ExecutorService executor = Executors.newFixedThreadPool(10); , how can I catch uncaught exception?

Thread.UncaughtExceptionHandler h = new Thread.UncaughtExceptionHandler() {
    public void uncaughtException(Thread th, Throwable ex) {
        System.out.println("Uncaught exception: " + ex);
    }
};

You can use the overload of the method newFixedThreadPool , which accepts a ThreadFactory :

Thread.UncaughtExceptionHandler eh = ...;
ThreadFactory factory = r -> {
    Thread t = new Thread(r);
    t.setUncaughtExceptionHandler(eh);
    return t;
};
ExecutorService executor = Executors.newFixedThreadPool(10, factory);

Adding to above answer, you can use Executors defaultThreadFactory and adding your own uncaughtExceptionHandler. It will give better management of threads.

ExecutorService executorService = Executors.newFixedThreadPool(10, runnable -> {
        Thread t = Executors.defaultThreadFactory().newThread(runnable);
        t.setUncaughtExceptionHandler((Thread th, Throwable e) -> {e.printStackTrace();});
        return t;
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM