Custom thread pool in Java 8 parallel stream

后端 未结 15 1274
旧巷少年郎
旧巷少年郎 2020-11-22 00:15

Is it possible to specify a custom thread pool for Java 8 parallel stream? I can not find it anywhere.

Imagine that I have a server application and I would like to

15条回答
  •  庸人自扰
    2020-11-22 01:10

    To measure the actual number of used threads, you can check Thread.activeCount():

        Runnable r = () -> IntStream
                .range(-42, +42)
                .parallel()
                .map(i -> Thread.activeCount())
                .max()
                .ifPresent(System.out::println);
    
        ForkJoinPool.commonPool().submit(r).join();
        new ForkJoinPool(42).submit(r).join();
    

    This can produce on a 4-core CPU an output like:

    5 // common pool
    23 // custom pool
    

    Without .parallel() it gives:

    3 // common pool
    4 // custom pool
    

提交回复
热议问题