Search code examples
javajava.util.concurrent

Is it not possible to supply a thread facory or name pattern to ForkJoinPool?


I would like to set name for threads of the ForkJoinPool used by work stealing pool, supplied by

ExecutorService newWorkStealingPool(int parallelism)

or

ExecutorService newWorkStealingPool()

So far I could not find a way to set custom names on threads used by this ExecutorService, is there a way?

newWorkStealingPool() basically supplies a ForkJoinPool, but ForkJoinPool also doesn't have a public constructor with supplied name pattern.

update: I have now found this constructor of ForkJoinPool which takes a thread factory ForkJoinPool.ForkJoinWorkerThreadFactory. But factory should return a ForkJoinWorkerThread, which doesn't have a public constructor. So I guess I will have to subclass ForkJoinWorkerThread.


Solution

  • This seems to be the minimum required code, reusing the existing default factory:

    final ForkJoinWorkerThreadFactory factory = new ForkJoinWorkerThreadFactory() {
      @Override         
      public ForkJoinWorkerThread newThread(ForkJoinPool pool) {
        final ForkJoinWorkerThread worker = ForkJoinPool.defaultForkJoinWorkerThreadFactory.newThread(pool);
        worker.setName("my-thread-prefix-name-" + worker.getPoolIndex());
        return worker;
      }
    };
            
    final ForkJoinPool forkJoinPool = new ForkJoinPool(Runtime.getRuntime().availableProcessors(), factory, null, false);
    

    Update for later JDK versions:

    final AtomicInteger index = new AtomicInteger();
    final ForkJoinPool.ForkJoinWorkerThreadFactory factory = pool -> {
      final ForkJoinWorkerThread worker = ForkJoinPool.defaultForkJoinWorkerThreadFactory.newThread(pool);
      worker.setName("my-thread-prefix-name-" + index.getAndIncrement());
      return worker;
    };
    
    final ForkJoinPool forkJoinPool = new ForkJoinPool(Runtime.getRuntime().availableProcessors(), factory, null, false);