在 ExecutorService 的提交和 ExecutorService 的执行之间进行选择 [英] Choose between ExecutorService's submit and ExecutorService's execute

查看:23
本文介绍了在 ExecutorService 的提交和 ExecutorService 的执行之间进行选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该如何选择 ExecutorService 的 提交execute,如果返回值不是我关心的?

如果我同时测试两者,除了返回值之外,我没有发现两者之间有任何差异.

ExecutorService threadExecutor = Executors.newSingleThreadExecutor();threadExecutor.execute(new Task());

<小时>

ExecutorService threadExecutor = Executors.newSingleThreadExecutor();threadExecutor.submit(new Task());

解决方案

在异常/错误处理方面存在差异.

使用execute() 排队的任务生成一些Throwable 将导致Thread 运行的UncaughtExceptionHandler要调用的任务.默认的 UncaughtExceptionHandler,通常将 Throwable 堆栈跟踪打印到 System.err,如果没有安装自定义处理程序,将被调用.>

另一方面,由 submit() 排队的任务生成的 Throwable 会将 Throwable 绑定到 Future 是通过调用 submit() 产生的.在那个 Future 上调用 get() 将抛出一个 ExecutionException 以原始 Throwable 作为其原因(可通过调用访问getCause() 上的 ExecutionException).

How should I choose between ExecutorService's submit or execute, if the returned value is not my concern?

If I test both, I didn't see any differences among the two except the returned value.

ExecutorService threadExecutor = Executors.newSingleThreadExecutor();
threadExecutor.execute(new Task());


ExecutorService threadExecutor = Executors.newSingleThreadExecutor();
threadExecutor.submit(new Task());

解决方案

There is a difference concerning exception/error handling.

A task queued with execute() that generates some Throwable will cause the UncaughtExceptionHandler for the Thread running the task to be invoked. The default UncaughtExceptionHandler, which typically prints the Throwable stack trace to System.err, will be invoked if no custom handler has been installed.

On the other hand, a Throwable generated by a task queued with submit() will bind the Throwable to the Future that was produced from the call to submit(). Calling get() on that Future will throw an ExecutionException with the original Throwable as its cause (accessible by calling getCause() on the ExecutionException).

这篇关于在 ExecutorService 的提交和 ExecutorService 的执行之间进行选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆