I'm using a ThreadPoolExecutor
in Java to manage a lot of running threads. I've created my own simple ThreadFactory
so I can give the threads better names.
The issue is that the name gets set in the Thread when the thread pool is first created and is not tied to the task that the thread pool is actually running. I understand this... my Runnables and Callables--though they have names--are actually one level of abstraction down from the ThreadPoolExecutor
's running threads.
There have been some other questions on StackOverflow about creating names for ThreadPoolExecutor
thread pools. (See How to give name to a callable Thread? and How to name the threads of a thread pool in Java.)
What I want to know is: does anyone have a good solution for keeping the name of the thread pool thread in sync with the Runnable that it is actually running?
i.e. If I call Thread.getCurrentThread().getName()
I'd like it not to return the name of the top-level thread pool, but rather the name of the Callable/Runnable that the thread is currently running.
Since this is mainly for debugging and logging purposes, I'm trying to avoid a solution that involves me putting new code into every Runnable that might be submitted to the ThreadPoolExecutor--I'd rather just put some code into the ThreadFactory or wrap the ThreadPoolExecutor itself so that the change is done in one place. If such a solution doesn't exist I probably won't bother since it's not mission critical.
begin edit To clarify, I know I can put a Thread.currentThread().setName( "my runnable name" );
as the first line of every Runnable's run method, but I'm trying to avoid doing that. I'm being a perfectionist here, and I realize it, so I won't be offended if people want to comment on this question and tell me so. end edit
My other question, I suppose, is whether people think it's a bad idea to do such a thing. Should I be wary of updating the thread pool name like this?
Thanks for any suggestions!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…