Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/324.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 8并行流中的自定义线程池_Java_Concurrency_Parallel Processing_Java 8_Java Stream - Fatal编程技术网

Java 8并行流中的自定义线程池

Java 8并行流中的自定义线程池,java,concurrency,parallel-processing,java-8,java-stream,Java,Concurrency,Parallel Processing,Java 8,Java Stream,是否可以为Java8指定自定义线程池?我到处都找不到 假设我有一个服务器应用程序,我想使用并行流。但是这个应用程序很大,而且是多线程的,所以我想对它进行划分。我不希望在applicationblock任务的一个模块中运行缓慢的任务从另一个模块开始 如果我不能为不同的模块使用不同的线程池,这意味着我不能在大多数实际情况下安全地使用并行流 试试下面的例子。在不同的线程中执行一些CPU密集型任务。 这些任务利用并行流。第一个任务已中断,因此每个步骤需要1秒(通过线程睡眠模拟)。问题是其他线程会被卡住,

是否可以为Java8指定自定义线程池?我到处都找不到

假设我有一个服务器应用程序,我想使用并行流。但是这个应用程序很大,而且是多线程的,所以我想对它进行划分。我不希望在applicationblock任务的一个模块中运行缓慢的任务从另一个模块开始

如果我不能为不同的模块使用不同的线程池,这意味着我不能在大多数实际情况下安全地使用并行流

试试下面的例子。在不同的线程中执行一些CPU密集型任务。 这些任务利用并行流。第一个任务已中断,因此每个步骤需要1秒(通过线程睡眠模拟)。问题是其他线程会被卡住,并等待中断的任务完成。这是一个虚构的示例,但想象一下一个servlet应用程序和一个人向共享fork-join池提交一个长时间运行的任务

public class ParallelTest {
    public static void main(String[] args) throws InterruptedException {
        ExecutorService es = Executors.newCachedThreadPool();

        es.execute(() -> runTask(1000)); //incorrect task
        es.execute(() -> runTask(0));
        es.execute(() -> runTask(0));
        es.execute(() -> runTask(0));
        es.execute(() -> runTask(0));
        es.execute(() -> runTask(0));


        es.shutdown();
        es.awaitTermination(60, TimeUnit.SECONDS);
    }

    private static void runTask(int delay) {
        range(1, 1_000_000).parallel().filter(ParallelTest::isPrime).peek(i -> Utils.sleep(delay)).max()
                .ifPresent(max -> System.out.println(Thread.currentThread() + " " + max));
    }

    public static boolean isPrime(long n) {
        return n > 1 && rangeClosed(2, (long) sqrt(n)).noneMatch(divisor -> n % divisor == 0);
    }
}

并行流使用默认的
ForkJoinPool.commonPool
,它由
Runtime.getRuntime().availableProcessors()
返回(这意味着并行流为调用线程保留一个处理器)

对于需要单独或自定义池的应用程序,可以使用给定的目标并行级别构造ForkJoinPool;默认情况下,等于可用处理器的数量

这也意味着,如果您同时启动了嵌套并行流或多个并行流,它们将共享同一个池。优点:您将永远不会使用超过默认值(可用处理器的数量)。缺点:您可能无法将“所有处理器”分配给您启动的每个并行流(如果您碰巧有多个处理器)。(显然,你可以使用一种方法来避免这种情况。)

要更改并行流的执行方式,您可以

  • 将并行流执行提交到您自己的ForkJoinPool:
    yourFJP.submit(()->stream.parallel().forEach(soSomething)).get()
  • 您可以使用系统属性更改公共池的大小:
    system.setProperty(“java.util.concurrent.ForkJoinPool.common.parallelism”,“20”)
    以获得20个线程的目标并行性。但是,在使用后端口补丁后,这将不再有效

我的机器上有8个处理器,这是后者的例子。如果我运行以下程序:

long start = System.currentTimeMillis();
IntStream s = IntStream.range(0, 20);
//System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism", "20");
s.parallel().forEach(i -> {
    try { Thread.sleep(100); } catch (Exception ignore) {}
    System.out.print((System.currentTimeMillis() - start) + " ");
});
输出为:

215216 216 216 216 216 216 216 316 316 316 415 416 416 416

因此您可以看到并行流一次处理8个项目,即它使用8个线程。但是,如果我取消注释注释行,则输出为:

215215215216 216 216 216 216 216 216 216 216 216 216 216 216 216 216 216 216 216 216 216 216 216 216 216 216 216 216


这一次,并行流使用了20个线程,流中的所有20个元素都被并发处理。

实际上有一个技巧,可以在特定的fork-join池中执行并行操作。如果将其作为fork-join池中的任务执行,它将留在那里,而不使用公共池

final int parallelism = 4;
ForkJoinPool forkJoinPool = null;
try {
    forkJoinPool = new ForkJoinPool(parallelism);
    final List<Integer> primes = forkJoinPool.submit(() ->
        // Parallel task here, for example
        IntStream.range(1, 1_000_000).parallel()
                .filter(PrimesPrint::isPrime)
                .boxed().collect(Collectors.toList())
    ).get();
    System.out.println(primes);
} catch (InterruptedException | ExecutionException e) {
    throw new RuntimeException(e);
} finally {
    if (forkJoinPool != null) {
        forkJoinPool.shutdown();
    }
}
final int parallelism=4;
ForkJoinPool-ForkJoinPool=null;
试一试{
forkJoinPool=新的forkJoinPool(并行);
最终列表primes=forkJoinPool.submit(()->
//例如,这里的并行任务
IntStream.range(1,1_000_000).parallel()
.filter(PrimesPrint::iPrime)
.boxed().collect(收集器.toList())
).get();
系统输出打印项次(素数);
}捕获(中断异常|执行异常e){
抛出新的运行时异常(e);
}最后{
if(forkJoinPool!=null){
forkJoinPool.shutdown();
}
}

该技巧基于以下指定:“安排在当前任务正在运行的池中异步执行此任务(如果适用),或者使用
ForkJoinPool.commonPool()
如果不是
inForkJoinPool()

除了触发您自己的forkJoinPool内的并行计算,您还可以将该池传递给CompletableFuture.SupplySync方法,如中所示:

ForkJoinPool forkJoinPool = new ForkJoinPool(2);
CompletableFuture<List<Integer>> primes = CompletableFuture.supplyAsync(() ->
    //parallel task here, for example
    range(1, 1_000_000).parallel().filter(PrimesPrint::isPrime).collect(toList()), 
    forkJoinPool
);
ForkJoinPool-ForkJoinPool=新的ForkJoinPool(2);
CompletableFuture素数=CompletableFuture.SupplySync(()->
//例如,这里的并行任务
范围(1,1_000_000).parallel().filter(PrimesPrint::isPrime).collect(toList()),
叉子池
);

要测量实际使用的线程数,可以检查
Thread.activeCount()

这可以在4核CPU上产生如下输出:

5 // common pool
23 // custom pool
如果没有
.parallel()
,它将提供:

3 // common pool
4 // custom pool

到目前为止,我使用了这个问题答案中描述的解决方案。现在,我想出了一个小图书馆,叫做:

ForkJoinPool pool = new ForkJoinPool(NR_OF_THREADS);
ParallelIntStreamSupport.range(1, 1_000_000, pool)
    .filter(PrimesPrint::isPrime)
    .collect(toList())
但正如@PabloMatiasGomez在评论中指出的,并行流的拆分机制存在缺陷,这在很大程度上取决于公共池的大小。看

我使用此解决方案只是为了让不同类型的工作有单独的池,但即使我不使用,也无法将公共池的大小设置为1。

原始解决方案(设置ForkJoinPool公共并行属性)不再有效。查看原始答案中的链接,一个打破这一点的更新已经被向后移植到Java8。正如链接线程中提到的,这个解决方案不能保证永远有效。基于此,解决方案是forkjoinpool.submit with.get解决方案,该解决方案在接受的答案中进行了讨论。我认为后端口也修复了此解决方案的不可靠性

ForkJoinPool fjpool = new ForkJoinPool(10);
System.out.println("stream.parallel");
IntStream range = IntStream.range(0, 20);
fjpool.submit(() -> range.parallel()
        .forEach((int theInt) ->
        {
            try { Thread.sleep(100); } catch (Exception ignore) {}
            System.out.println(Thread.currentThread().getName() + " -- " + theInt);
        })).get();
System.out.println("list.parallelStream");
int [] array = IntStream.range(0, 20).toArray();
List<Integer> list = new ArrayList<>();
for (int theInt: array)
{
    list.add(theInt);
}
fjpool.submit(() -> list.parallelStream()
        .forEach((theInt) ->
        {
            try { Thread.sleep(100); } catch (Exception ignore) {}
            System.out.println(Thread.currentThread().getName() + " -- " + theInt);
        })).get();
ForkJoinPool fjpool=新的ForkJoinPool(10);
System.out.println(“stream.parallel”);
IntStream range=IntStream.range(0,20);
fjpool.submit(()->range.parallel()
.forEach((int)->
{
尝试{Thread.sleep(100);}catch(异常忽略){}
System.out.println(Thread.currentThread().getName()+“--”+theInt);
})).get();
System.out.println(“list.paralle
ForkJoinPool fjpool = new ForkJoinPool(10);
System.out.println("stream.parallel");
IntStream range = IntStream.range(0, 20);
fjpool.submit(() -> range.parallel()
        .forEach((int theInt) ->
        {
            try { Thread.sleep(100); } catch (Exception ignore) {}
            System.out.println(Thread.currentThread().getName() + " -- " + theInt);
        })).get();
System.out.println("list.parallelStream");
int [] array = IntStream.range(0, 20).toArray();
List<Integer> list = new ArrayList<>();
for (int theInt: array)
{
    list.add(theInt);
}
fjpool.submit(() -> list.parallelStream()
        .forEach((theInt) ->
        {
            try { Thread.sleep(100); } catch (Exception ignore) {}
            System.out.println(Thread.currentThread().getName() + " -- " + theInt);
        })).get();
LongStream.range(4, 1_000_000).parallel(threadNum)...
 ReactiveSeq.range(1, 1_000_000)
            .foldParallel(new ForkJoinPool(10),
                          s->s.filter(i->true)
                              .peek(i->System.out.println("Thread " + Thread.currentThread().getId()))
                              .max(Comparator.naturalOrder()));
 ReactiveSeq.range(1, 1_000_000)
            .parallel(new ForkJoinPool(10),
                      s->s.filter(i->true)
                          .peek(i->System.out.println("Thread " + Thread.currentThread().getId())))
            .map(this::processSequentially)
            .forEach(System.out::println);
private static Set<String> ThreadNameSet = new HashSet<>();
private static Callable<Long> getSum() {
    List<Long> aList = LongStream.rangeClosed(0, 10_000_000).boxed().collect(Collectors.toList());
    return () -> aList.parallelStream()
            .peek((i) -> {
                String threadName = Thread.currentThread().getName();
                ThreadNameSet.add(threadName);
            })
            .reduce(0L, Long::sum);
}

private static void testForkJoinPool() {
    final int parallelism = 10;

    ForkJoinPool forkJoinPool = null;
    Long result = 0L;
    try {
        forkJoinPool = new ForkJoinPool(parallelism);
        result = forkJoinPool.submit(getSum()).get(); //this makes it an overall blocking call

    } catch (InterruptedException | ExecutionException e) {
        e.printStackTrace();
    } finally {
        if (forkJoinPool != null) {
            forkJoinPool.shutdown(); //always remember to shutdown the pool
        }
    }
    out.println(result);
    out.println(ThreadNameSet);
}
50000005000000
[ForkJoinPool-1-worker-8, ForkJoinPool-1-worker-9, ForkJoinPool-1-worker-6, ForkJoinPool-1-worker-11, ForkJoinPool-1-worker-10, ForkJoinPool-1-worker-1, ForkJoinPool-1-worker-15, ForkJoinPool-1-worker-13, ForkJoinPool-1-worker-4, ForkJoinPool-1-worker-2]
BlockingDeque blockingDeque = new LinkedBlockingDeque(1000);
ThreadPoolExecutor fixedSizePool = new ThreadPoolExecutor(10, 20, 60, TimeUnit.SECONDS, blockingDeque, new MyThreadFactory("my-thread"));
List<Path> paths = List.of("/path/file1.csv", "/path/file2.csv", "/path/file3.csv").stream().map(e -> Paths.get(e)).collect(toList());
List<List<Path>> partitions = Lists.partition(paths, 4); // Guava method

partitions.forEach(group -> group.parallelStream().forEach(csvFilePath -> {
       // do your processing   
}));
list.stream()
  .collect(parallel(i -> process(i), executor, 4))
  .join()
-Djava.util.concurrent.ForkJoinPool.common.parallelism=16
public ForkJoinPool(int parallelism,
                        ForkJoinWorkerThreadFactory factory,
                        UncaughtExceptionHandler handler,
                        boolean asyncMode) {
        this(checkParallelism(parallelism),
             checkFactory(factory),
             handler,
             asyncMode ? FIFO_QUEUE : LIFO_QUEUE,
             "ForkJoinPool-" + nextPoolId() + "-worker-");
        checkPermission();
    }
System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism", "2");
Set<String> threadNames = Stream.iterate(0, n -> n + 1)
  .parallel()
  .limit(100000)
  .map(i -> Thread.currentThread().getName())
  .collect(Collectors.toSet());
System.out.println(threadNames);

// Output -> [ForkJoinPool.commonPool-worker-1, Test worker, ForkJoinPool.commonPool-worker-3]