使用CompletableFuture安全吗?异步任务的正确执行是否得到保证?

huangapple go评论73阅读模式
英文:

Is using CompletableFuture safe? Will the correct execution of the async task be guaranteed?

问题

我想使用Java 8中的异步模式CompletableFuture来处理servlet。

但是找到了以下信息:

>线程的创建在EJB规范中是被禁止的。为了使容器更加稳健,应该在整个服务器进程中禁止线程的创建。将线程的创建从EJB转移到例如Servlets并不是一个合理的解决方案。
>
> ...
>
> 企业bean不能尝试管理线程。企业bean不能尝试启动、停止、挂起或恢复线程,也不能更改线程的优先级或名称。企业bean不能尝试管理线程组。"

使用CompletableFuture是否安全?是否能够保证异步任务的正确执行?

英文:

I wanted to use Asynchronous mode CompletableFuture Java 8 for servlet.

But found information:

>Thread creation is only prohibited in the EJB spec. To make the container more robust, it should be prohibited in the whole server process. Moving the thread creation from the EJBs to e.g. Servlets is not a reasonable solution.
>
> ...
>
> The enterprise bean must not attempt to manage threads. The enterprise bean must not attempt to start, stop, suspend, or resume a thread, or to change a thread’s priority or name. The enterprise bean must not attempt to manage thread groups."

Is using CompletableFuture safe? Will the correct execution of the async task be guaranteed?

答案1

得分: 2

如评论中所述,这取决于您计划如何使用它。

在EE环境中,唯一合法的线程池/执行器服务是托管执行器:

https://docs.oracle.com/javaee/7/api/javax/enterprise/concurrent/ManagedExecutorService.html

它是托管的,因为它是由服务器管理和提供的资源,可以在您的EJB中进行注入。

@Resource(name = "wm/executorService")
ManagedExecutorService managedExecutorService;

在注入了这样的资源后,您就有资格在提供此托管执行器的情况下运行CompletableFuture的异步方法:

CompletableFuture<Void> result = CompletableFuture.runAsync(
                        yourBean::yourMethod,
                        managedExecutorService);
英文:

As mentioned in comments, it depends on how do you plan to use it.

In EE environment the only legal thread pool / executor service is managed executor:

https://docs.oracle.com/javaee/7/api/javax/enterprise/concurrent/ManagedExecutorService.html

Managed, because it's a resource managed and provided by server and could be injected in your EJBs.

@Resource(name = &quot;wm/executorService&quot;)
ManagedExecutorService managedExecutorService;

Having injected such resource, you are eligible to run async methods of CompletableFuture providing this managed executor explicitly:

CompletableFuture&lt;Void&gt; result = CompletableFuture.runAsync(
                        yourBean::yourMethod,
                        managedExecutorService);

huangapple
  • 本文由 发表于 2020年4月3日 20:31:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/61011980.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定