JavaEE应用服务器中的CompletableFuture / parallelStream

时间:2016-03-31 16:09:38

标签: java java-ee asynchronous java-ee-7 completable-future

鉴于新的Java8,我们为异步任务获得了非常好的功能,例如: CompletableFuture和.paralellStream()。如果你在Java SE中运行它,因为我已经理解它你将使用ForkJoinPool,但是如果我在例如运行以下示例中会发生什么? Wildfly还是TomcatEE?

//Here I start a comp.Future without giving an Executor
test = CompletableFuture.supplyAsync(() -> timeConsumingMethod());
//Here I start a parallel stream 
mList.paralell().filter(...).collect(Collectors.toList())

如果

,我会从哪里借用资源
  1. 示例在@Stateful bean
  2. 中运行
  3. 示例在@Stateless bean
  4. 中运行
  5. 示例在CDI bean中运行

1 个答案:

答案 0 :(得分:8)

您不应在Java EE中使用ForkJoinPool。只有app服务器应该提供并行性的构造(如Java EE 7中的ManagedExecutorService),因为threads have to be managed by the container

奇怪的是,this answer中提到的邮件列表中有一条消息声称ForkJoinPool会优雅地降级为EE容器中的单线程。我用glassfish 4.1对此进行了测试,并创建了常用的线程。运行此代码:

@Singleton
public class SomeSingleton {
    public void fireStream() {
        IntStream.range(0, 32)
            .parallel()
            .mapToObj(i -> String.format("Task %d on thread %s", 
                i, Thread.currentThread().getName()))
            .forEach(System.out::println);
    }
}

我得到以下输出:

Info:   Task 20 on thread http-listener-1(4)
Info:   Task 10 on thread ForkJoinPool.commonPool-worker-3
Info:   Task 21 on thread http-listener-1(4)
Info:   Task 11 on thread ForkJoinPool.commonPool-worker-3
Info:   Task 22 on thread http-listener-1(4)
Info:   Task 8 on thread ForkJoinPool.commonPool-worker-3
Info:   Task 23 on thread http-listener-1(4)
Info:   Task 9 on thread ForkJoinPool.commonPool-worker-3
Info:   Task 18 on thread http-listener-1(4)
Info:   Task 14 on thread ForkJoinPool.commonPool-worker-3
Info:   Task 19 on thread http-listener-1(4)
Info:   Task 15 on thread ForkJoinPool.commonPool-worker-3
Info:   Task 16 on thread http-listener-1(4)
Info:   Task 17 on thread http-listener-1(4)
Info:   Task 4 on thread http-listener-1(4)
Info:   Task 5 on thread http-listener-1(4)
Info:   Task 6 on thread http-listener-1(4)
Info:   Task 7 on thread http-listener-1(4)
Info:   Task 2 on thread http-listener-1(4)
Info:   Task 3 on thread http-listener-1(4)
Info:   Task 0 on thread http-listener-1(4)
Info:   Task 1 on thread http-listener-1(4)
Info:   Task 26 on thread http-listener-1(4)
Info:   Task 27 on thread http-listener-1(4)
Info:   Task 24 on thread http-listener-1(4)
Info:   Task 25 on thread http-listener-1(4)
Info:   Task 12 on thread http-listener-1(4)
Info:   Task 13 on thread http-listener-1(4)
Info:   Task 30 on thread http-listener-1(4)
Info:   Task 31 on thread http-listener-1(4)
Info:   Task 28 on thread ForkJoinPool.commonPool-worker-0
Info:   Task 29 on thread ForkJoinPool.commonPool-worker-0

当大多数个别规范将利用SE 8功能时,Java EE 8上可能会出现降级。

修改

我已检查了glassfish 4.1.1源代码,并且没有ForkJoinPoolForkJoinWorkerThreadFactoryForkJoinWorkerThread的使用。因此,应用服务器管理的并行性资源不是基于任何这些结构。不幸的是,确实没有可用的退化机制。