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, 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 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);