Reputation: 17785
It is possible to create various type of Thread Executors in Java, singleThreadedExecutor
, fixedThreadedExecutor
etc. Is there any way I can add something so that when I invoke getThreadName()
and getThreadID()
on an executing thread, I can see what Thread executor it has come from?
Thanks.
Upvotes: 1
Views: 238
Reputation: 340763
If you are using guava, it's quite simple:
final ThreadFactory threadFactory = new ThreadFactoryBuilder()
.setNameFormat("Fancy-pool-%02d")
.build();
Executors.newFixedThreadPool(10, threadFactory);
If you are not a happy guava user, you can implement it yourself:
final ThreadFactory threadFactory = new ThreadFactory() {
final AtomicInteger id = new AtomicInteger();
@Override
public Thread newThread(Runnable r) {
final Thread thread = new Thread(r);
thread.setName("Fancy-pool-" + id.incrementAndGet());
return thread;
}
};
Upvotes: 1
Reputation: 116888
If you are taking about the names of the threads when the submitted tasks are running then I'd recommend using a ThreadGroup
. You could also use a ThreadLocal
but that sounds more like a hack.
To use the ThreadGroup
you would need to inject your own ThreadFactory
to the executor.
final ThreadGroup threadGroup = new ThreadGroup("someThreadPoolName");
threadPool = Executors.newFixedThreadPool(10, new ThreadFactory() {
public Thread newThread(Runnable r) {
Thread thread = new Thread(threadGroup, r);
return thread;
}
});
Then a thread could do:
String myThreadPollName = Thread.currentThread().getThreadGroup().getName();
Upvotes: 1
Reputation: 66886
Yes. You supply these factory methods with a ThreadFactory
implementation. This is a thing that makes a Thread
from a Runnable
. So you can do whatever you like in the method, such as set its name, priority or daemon status -- even employ a custom Thread
subclass.
Upvotes: 1