0

If I am extending an existing ThreadFactory implementation, how would I go able ensuring that all threads created would have the same prefix? I'm sick and tired of looking at Thread-9 in my logs and would like to distinguish between threads more easily.

Does anyone have any suggestions as to how to go about this?

Elijah
  • 13,030
  • 9
  • 56
  • 88

3 Answers3

5

Provide your own implementation of the ThreadFactory interface:

pool = Executors.newScheduledThreadPool(numberOfThreads, new TF());

class TF implements ThreadFactory {
    public synchronized Thread newThread(Runnable r) {
        Thread t = new Thread(r) ;
        t.setName("Something here....");  
        return t;
    }
}
PaulJWilliams
  • 18,549
  • 3
  • 49
  • 78
  • Thanks for the example. However, the API I am using only allows me to specify the ThreadPool class implementation and not the ThreadFactory implementation. – Elijah Apr 28 '09 at 13:12
  • What do you mean by ThreadPool class ? Which interface do you have to work with ? Executor ? – Brian Agnew Apr 28 '09 at 13:16
  • Wow. I feel stupid. ThreadPool is an interface in Quartz. Thank you for your answer. I think it will be useful. I'm going to update the question. – Elijah Apr 28 '09 at 14:24
1

You should use your own custom thread factory. The default factories are not much of use. Implement a ThreadFactoryBuilder to create you custom thread factories that allows you to do the following:

  1. Have custom thread names
  2. Have choice of threads - User or Daemon threads
  3. Have choice of Thread Priority
  4. Have flexibility to set uncaught exception handlers

You have a sample ThreadFactoryBuilder implementation in the following post which you can use.

http://wilddiary.com/understanding-java-threadfactory-creating-custom-thread-factories/

Drona
  • 6,482
  • 1
  • 27
  • 35
0

Can you provide your own ThreadFactory ? That will allow you to create threads with whatever naming convention you require.

Brian Agnew
  • 261,477
  • 36
  • 323
  • 432