Naming threads and thread-pools of ExecutorService Naming threads and thread-pools of ExecutorService java java

Naming threads and thread-pools of ExecutorService


Guava almost always has what you need.

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

and pass it off to your ExecutorService.


You could supply a ThreadFactory to newSingleThreadScheduledExecutor(ThreadFactory threadFactory). The factory will be responsibe for creating threads, and will be able to name them.

To quote the Javadoc:

Creating new threads

New threads are created using a ThreadFactory. If not otherwise specified, a Executors.defaultThreadFactory() is used, that creates threads to all be in the same ThreadGroup and with the same NORM_PRIORITY priority and non-daemon status. By supplying a different ThreadFactory, you can alter the thread's name, thread group, priority, daemon status, etc. If a ThreadFactory fails to create a thread when asked by returning null from newThread, the executor will continue, but might not be able to execute any tasks


You can try to provide your own thread factory, which will create thread with appropriate names. Here's one example:

class YourThreadFactory implements ThreadFactory {   public Thread newThread(Runnable r) {     return new Thread(r, "Your name");   } }Executors.newSingleThreadExecutor(new YourThreadFactory()).submit(someRunnable);