Naming threads and thread-pools of ExecutorService
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);
Or in Kotlin
Executors.newSingleThreadExecutor { r -> Thread(r, "Your name") }
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, aExecutors.defaultThreadFactory()
is used, that creates threads to all be in the sameThreadGroup
and with the sameNORM_PRIORITY
priority and non-daemon status. By supplying a differentThreadFactory
, you can alter the thread's name, thread group, priority, daemon status, etc. If aThreadFactory
fails to create a thread when asked by returning null fromnewThread
, the executor will continue, but might not be able to execute any tasks
You can also change the name of your thread afterwards, while the thread is executed:
Thread.currentThread().setName("FooName");
That could be of interest if for instance you're using the same ThreadFactory for different type of tasks.
Guava almost always has what you need.
ThreadFactory namedThreadFactory =
new ThreadFactoryBuilder().setNameFormat("my-sad-thread-%d").build()
and pass it off to your ExecutorService
.