Naming threads and thread-pools of ExecutorService

mre picture mre · May 24, 2011 · Viewed 133.6k times · Source

Let's say I have an application that utilizes the Executor framework as such

Executors.newSingleThreadExecutor().submit(new Runnable(){
    @Override
    public void run(){
        // do stuff
    }
}

When I run this application in the debugger, a thread is created with the following (default) name: Thread[pool-1-thread-1]. As you can see, this isn't terribly useful and as far as I can tell, the Executor framework does not provide an easy way to name the created threads or thread-pools.

So, how does one go about providing names for the threads/thread-pools? For instance, Thread[FooPool-FooThread].

Answer

pathikrit picture pathikrit · Mar 17, 2012

Guava almost always has what you need.

ThreadFactory namedThreadFactory = 
  new ThreadFactoryBuilder().setNameFormat("my-sad-thread-%d").build()

and pass it off to your ExecutorService.