Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to set the priority of the threads in Stream.parallel()?

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?

like image 810
Stephane Grenier Avatar asked Nov 26 '17 03:11

Stephane Grenier


2 Answers

I think a better way to do this is like described here:

public class CustomForkJoinWorkerThreadFactory implements ForkJoinWorkerThreadFactory {

    private final int threadPriority;

    public CustomForkJoinWorkerThreadFactory(int threadPriority) {
        this.threadPriority = threadPriority;
    }

    @Override           
    public ForkJoinWorkerThread newThread(ForkJoinPool pool)
    {
        final ForkJoinWorkerThread worker = ForkJoinPool.defaultForkJoinWorkerThreadFactory.newThread(pool);
        worker.setPriority(threadPriority);
        return worker;
    }
}

It allows you to still use a "default" ForkJoinWorkerThread, but you can set priority / name / etc. Use like this:

new ForkJoinPool(poolSize, new CustomForkJoinWorkerThreadFactory(Thread.MIN_PRIORITY), null, false);
like image 144
Katharsas Avatar answered Sep 22 '22 12:09

Katharsas


Yes it is possible.

The procedure is as follows:

  1. Create a ForkJoinWorkerThreadFactory that creates threads with an appropriate priority.

  2. Create a ForkJoinPool using the above thread factory.

  3. Instantiate the parallel stream.

  4. 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)

like image 22
Stephen C Avatar answered Sep 20 '22 12:09

Stephen C