I have a list of tasks. Each task is independent of each other (they do not use results from each other).
When having 1000 tasks and using a sequential stream to process these tasks..
tasks.forEach(task->{
// long running task
task.run();
System.out.println("Thread: " + Thread.currentThread().getName());
});
..then, the second task is running AFTER the first task and so forth. The loop is running in blocking and sequential mode (second task is only done after first task is finished).
What is the best way to process each task in parallel?
Is this the best way?
tasks.parallelStream().forEach(task->{
// long running task
task.run();
System.out.println("Thread: " + Thread.currentThread().getName());
});
According to Should I always use a parallel stream when possible?, it should be avoided to use parallel streams. As in my case, these tasks are independent of each other, I do not need the synchronization overhead which comes by using parallelStream()
. However, there is no option to disable the synchronization overhead when using parallelStream()
. Or?
Is there a better way for my use case than parallelStream()
?