task id as thread name in thread pool

java, multithreading, threadpool

Solution

You can set the name of the thread executing your task as:

class YourTask implements Runnable {
  public void run() {
    Thread.currentThread().setName(getTaskId());
    //.. rest of the code for the task
  }
}

This is probably what you want anyway. A thread that is created by the thread pool might be used for executing many different tasks - so giving the thread a name which is dependent on the task that it will eventually run is not possible.

Problem

I need to create a thread from the thread pool and need to pass a task id - a unique id that kept in my `Runnable` object - as the thread name. I looked in to the `ThreadFactory` interface, but in that I couldn't pass any additional parameter as thread name to the thread created. Also, I looked at the `DefaultThreadFactory` class. It uses an `AtomicInteger` to set the thread name. Can I pass an arbitrary string to the factory and have it use that string as the name of the thread created?

Original source