Java – fork and join without main thread

I want to use the thread pool to process the list of items and wait for them to finish If not, I also need to be able to time it after 4 minutes

This is what I have now

ForkJoinPool threadPool = new ForkJoinPool(Runtime.getRuntime().availableProcessors() * 2);

list.forEach(entry -> threadPool.execute(() -> {
    // processing
}));

if (!threadPool.awaitQuiescence(4,TimeUnit.MINUTES)) {
    // send alert about delay
}

The problem is that sometimes this method will use the main thread to process one of the list items, which means that awaitquiet will not start until it is completed Is there any other thread pool that allows similar things, but guarantees not to use the main thread, or is there a way to configure forkjoinpool?

Solution

I think the problem is that you still iterate in the main thread (list. Foreach) Use parallel streams and delegate the entire computation to your pool:

ForkJoinPool pool = new ForkJoinPool(Runtime.getRuntime().availableProcessors() * 2);

pool.execute(() -> {
    list.parallelStream().forEach(item -> {
        // processing
    });
});

if (!pool.awaitQuiescence(4L,TimeUnit.MINUTES)) {
    // send alert about delay
}

I recommend reading this question (and the given answer) to learn how to use forkjoinpool and parallel flow

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>