Stephane Grenier :
If I want to run a Stream in parallel in a background task is it possible to run it in lower priority? And if so how?
Stephen C :
Yes it is possible.
The procedure is as follows:
Create a
ForkJoinWorkerThreadFactory
that creates threads with an appropriate priority.Create a
ForkJoinPool
using the above thread factory.Instantiate the parallel stream.
Run the stream by submitting it to the
ForkJoinPool
Something like this:
public class MyThread extends ForkJoinWorkerThread {
public MyThread(ForkJoinPool pool, int priority) {
super(pool);
setPriority(priority);
}
}
final int poolSize = ...
final int priority = ...
List<Long> aList = LongStream.rangeClosed(firstNum, lastNum).boxed()
.collect(Collectors.toList());
ForkJoinWorkerThreadFactory factory = new ForkJoinWorkerThreadFactory() {
public ForkJoinWorkerThread newThread(ForkJoinPool pool) {
return new MyThread(pool, priority);
}
};
/*
ForkJoinWorkerThreadFactory factory = pool -> new MyThread(
pool,
priority
);
*/
ForkJoinPool customThreadPool = new ForkJoinPool(
poolSize, factory, null, false);
long actualTotal = customThreadPool.submit(
() -> aList.parallelStream().reduce(0L, Long::sum)).get();
(Example code adapted from http://www.baeldung.com/java-8-parallel-streams-custom-threadpool)
Guess you like
Origin http://10.200.1.11:23101/article/api/json?id=435551&siteId=1