CompletableFuture/parallelStream 在 JavaEE 应用程序服务器中

CompletableFuture/parallelStream in JavaEE app server

鉴于新的 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. CDI bean
  5. 中的例子是运行

你不应该在 Java EE 中使用 ForkJoinPool。只有应用服务器应该提供并行结构(如 ManagedExecutorService in Java EE 7), because 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

也许降级将在 Java EE 8 上可用,届时大多数单独的规范将利用 SE 8 功能。


编辑

我查看了 glassfish 4.1.1 源代码,没有单独使用 ForkJoinPoolForkJoinWorkerThreadFactoryForkJoinWorkerThread。因此,应用服务器管理的并行资源不基于任何这些结构。不幸的是,确实没有可用的降级机制。