How to catch exceptions in FutureTask

前端 未结 5 736
小蘑菇
小蘑菇 2020-12-06 04:42

After finding that FutureTask running in a Executors.newCachedThreadPool() on Java 1.6 (and from Eclipse) swallows exceptions in the Runnable

5条回答
  •  北海茫月
    2020-12-06 04:59

    setException probably isn't made for overriding, but is provided to let you set the result to an exception, should the need arise. What you want to do is override the done() method and try to get the result:

    public class MyFutureTask extends FutureTask {
    
        public MyFutureTask(Runnable r) {
            super(r, null);
        }
    
        @Override
        protected void done() {
            try {
                if (!isCancelled()) get();
            } catch (ExecutionException e) {
                // Exception occurred, deal with it
                System.out.println("Exception: " + e.getCause());
            } catch (InterruptedException e) {
                // Shouldn't happen, we're invoked when computation is finished
                throw new AssertionError(e);
            }
        }
    }
    
        

    提交回复
    热议问题