Is it discouraged using Java 8 parallel streams inside a Java EE container?

前端 未结 2 750
死守一世寂寞
死守一世寂寞 2020-12-05 00:43

Given that spawning threads in Java EE containers are discouraged. Would using the Java 8 parallel streams, which may spawn threads, inside Java EE be discouraged too?

2条回答
  •  一生所求
    2020-12-05 00:46

    A heads up, the graceful degradation to single thread is not available. I also thought it was because of Shorn's answer and that mailing list discussion, but I found out it wasn't while researching for this question. The mechanism is not in the Java EE 7 spec and it's not in glassfish 4.1. Even if another container does it, it won't be portable.

    You can test this by calling the following method:

    @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);
        }
    }
    

    And you'll get something like:

    Info:   Task 20 on thread http-listener-1(4)
    Info:   Task 10 on thread ForkJoinPool.commonPool-worker-3
    Info:   Task 28 on thread ForkJoinPool.commonPool-worker-0
    ...
    

    I've also checked glassfish 4.1.1 source code, and there isn't a single use of ForkJoinPool, ForkJoinWorkerThreadFactory or ForkJoinWorkerThread.

    The mechanism could be added to EE 8, since many frameworks will leverage jdk8 features, but I don't know if it's part of the spec.

提交回复
热议问题