11

Can we set java.util.concurrent.ForkJoinPool.common.parallelism java property?

System.out.println("getParallelism=" +ForkJoinPool.commonPool().getParallelism());
System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism","20");
Thread.sleep(1000);
System.out.println("getParallelism=" +ForkJoinPool.commonPool().getParallelism());

prints:

getParallelism=3
getParallelism=3 
Stav Alfi
  • 13,139
  • 23
  • 99
  • 171
  • If you change the second line to `System.out.println(System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism","20"));`, does it indicate a previous value of 3 for that property? – jsheeran Feb 27 '18 at 13:26
  • 1
    The common parallelism property is set once per initialization of class `ForkJoinPool` , and cannot be changed at runtime. – M. Prokhorov Feb 27 '18 at 13:28
  • I think while creating your ForkJoinPool you can pass this value to the factory method. – Naresh Joshi Feb 27 '18 at 13:29
  • @NareshJoshi, that is true, but there is no ability to affect the `commonPool()` like that. – M. Prokhorov Feb 27 '18 at 13:31

3 Answers3

18

You have to set the parameter before the application starts. So passing a JVM parameter

-Djava.util.concurrent.ForkJoinPool.common.parallelism=20

at startup will change it to 20.

Can't Tell
  • 12,714
  • 9
  • 63
  • 91
4

Otherwise you can create your custom pool and achieve the parallelism you want

int numTasks = 20;
ForkJoinPool pool = new ForkJoinPool(numTasks);
System.out.println("getCustomParallelism=" +pool.getParallelism()); //prints 20
Hasnaa Ibraheem
  • 1,132
  • 1
  • 10
  • 18
  • When this question was asked, I was trying to override the number of threads that were used in Stream.parallel() so overring the default pool is the only solution (at least, that's what I know) – Stav Alfi May 01 '19 at 05:18
  • 1
    Aha, I can get your point now. I found this link to help in your situation: https://stackoverflow.com/questions/21163108/custom-thread-pool-in-java-8-parallel-stream – Hasnaa Ibraheem May 01 '19 at 08:49
2

The dynamic setting works when it is the first statement accessing the pool. Try removing the first line which gets and prints the default parallelism. Use just the below.

    System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism","20");
    System.out.println("getParallelism=" +ForkJoinPool.commonPool().getParallelism());
Sudhakumar
  • 21
  • 1