How to catch exceptions in FutureTask

前端 未结 5 734
小蘑菇
小蘑菇 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 05:09

    Have you tried using an UncaughtExceptionHandler?

    • You need to implement the UncaughtExceptionHandler interface.
    • To set an UncaughtExceptionHandler for pool threads, provide a ThreadFactory in the Executor.newCachedThreadPool(ThreadFactory) call.
    • You can set the UncaughtExceptionHandler for the created thread via setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler eh)

    Submit the tasks with ExecutorService.execute, because only exceptions thrown from tasks submitted with execute make it to the uncaught exception handler. For Tasks submitted with ExecutorService.submit any thrown exception is considered to be part of the task's return value. If a task submitted with submit terminates with an exception, it is rethrown when calling Future.get, wrapped in an ExecutionException

提交回复
热议问题