How to properly catch RuntimeExceptions from Executors?

前端 未结 5 1854
青春惊慌失措
青春惊慌失措 2020-12-12 20:44

Say that I have the following code:

ExecutorService executor = Executors.newSingleThreadExecutor();
executor.execute(myRunnable);

Now, if <

5条回答
  •  无人及你
    2020-12-12 21:16

    skaffman is correct in that using submit is the cleanest approach. An alternative approach is to subclass ThreadPoolExecutor and override afterExecute(Runnable, Throwable). If you follow this approach be sure to call execute(Runnable) rather than submit(Runnable) or afterExecute will not be invoked.

    Per the API description:

    Method invoked upon completion of execution of the given Runnable. This method is invoked by the thread that executed the task. If non-null, the Throwable is the uncaught RuntimeException or Error that caused execution to terminate abruptly.

    Note: When actions are enclosed in tasks (such as FutureTask) either explicitly or via methods such as submit, these task objects catch and maintain computational exceptions, and so they do not cause abrupt termination, and the internal exceptions are not passed to this method.

提交回复
热议问题