1

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.

1

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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(); 

Comments

1

If you are using , it's quite simple:

final ThreadFactory threadFactory = new ThreadFactoryBuilder() .setNameFormat("Fancy-pool-%02d") .build(); Executors.newFixedThreadPool(10, threadFactory); 

If you are not a happy 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; } }; 

See also:

2 Comments

do you really need to use an Atomic Integer there? I am not clear if the thread factory will have concurrency access or not. It is only making threads - not running them. yeah? Also surely you need to increase it each time as well.
@dublintech: I based this example on how both Guava and JDK implement thread factory. Also it's possible that two threads concurrently submit some task and suddenly thread pool needs to create two threads to satisfy growing demand. Race condition may occur. Thanks for four tip about incrementing the counter, fixed.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.