Why is UncaughtExceptionHandler not called by ExecutorService?

前端 未结 6 2092
你的背包
你的背包 2020-12-23 09:01

I\'ve stumbled upon a problem, that can be summarized as follows:

When I create the thread manually (i.e. by instantiating java.lang.Thread) the U

6条回答
  •  清酒与你
    2020-12-23 10:03

    Quote from the book Java Concurrency in Practice(page 163),hope this helps

    Somewhat confusingly, exceptions thrown from tasks make it to the uncaught exception handler only for tasks submitted with execute; for tasks submitted with submit, any thrown exception, checked or not, is considered to be part of the task’s return status. If a task submitted with submit terminates with an exception, it is rethrown by Future.get, wrapped in an ExecutionException.

    Here is the example:

    public class Main {
    
    public static void main(String[] args){
    
    
        ThreadFactory factory = new ThreadFactory(){
    
            @Override
            public Thread newThread(Runnable r) {
                // TODO Auto-generated method stub
                final Thread thread =new Thread(r);
    
                thread.setUncaughtExceptionHandler( new Thread.UncaughtExceptionHandler() {
    
                    @Override
                    public void uncaughtException(Thread t, Throwable e) {
                        // TODO Auto-generated method stub
                        System.out.println("in exception handler");
                    }
                });
    
                return thread;
            }
    
        };
    
        ExecutorService pool=Executors.newSingleThreadExecutor(factory);
        pool.execute(new testTask());
    
    }
    
    
    
    private static class TestTask implements Runnable {
    
        @Override
        public void run() {
            // TODO Auto-generated method stub
            throw new RuntimeException();
        }
    
    }
    

    I use execute to submit the task and the console outputs "in exception handler"

提交回复
热议问题