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

那年仲夏 提交于 2019-12-05 03:21:53

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;
    }
};

forkJoinPool = new ForkJoinPool(Runtime.getRuntime().availableProcessors(), factory, null, false); 

(Answering your update)

The following should allow you full control over the threads produced by your ForkJoinPools. In my case I wanted to be able to do "dangerous" stuff like access system properties. The default implementation uses java.util.concurrent.ForkJoinWorkerThread.InnocuousForkJoinWorkerThread which has a security manager and zero permissions.

public class MyForkJoinThreadFactory implements ForkJoinPool.ForkJoinWorkerThreadFactory {
  @Override
  public ForkJoinWorkerThread newThread(ForkJoinPool pool) {
    return new NotSoInnocuousWorkerThread(pool);
  }
}

and the worker thread (that now has all the same permissions as the rest of your application is this like this, plus whatever else you wanted....

public class NotSoInnocuousWorkerThread extends ForkJoinWorkerThread {
  protected NotSoInnocuousWorkerThread(ForkJoinPool pool) {
    super(pool);
  }
}

And you need to either pass the following property or set it in your code like this:

System.setProperty("java.util.concurrent.ForkJoinPool.common.threadFactory", 
                   MyForkJoinThreadFactory.class.getName());
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!