问题
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
.
回答1:
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);
回答2:
(Answering your update)
The following should allow you full control over the threads produced by your ForkJoinPool
s. 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());
来源:https://stackoverflow.com/questions/34303094/is-it-not-possible-to-supply-a-thread-facory-or-name-pattern-to-forkjoinpool