We h开发者_运维百科ave a Java application that processes requests. Naturally, there is a thread pool with threads named with some insignificant names like "processor-1", "processor-2" etc. We are wondering whether it's a good idea to rename the processing thread each time it gets a request to a name that would indicate which request is being processed.
I have a feeling that something is wrong about it, but cannot think of a good reason. I can remember several cases of analyzing multi-threading issues from thread dumps and it was very important to me to know whether I see the same thread in two consecutive dumps or not. However, I realize that I could look at the thread ID instead. In log4j logs it's a common practice to write the thread name and I remember many cases of filtering by it. But still I'm not sure I have a good "line of defense" here.
What is the common practice? Is it a good idea to keep renaming threads?
There are related questions like Renaming Threads in Java or Should threads in Java be named for easier debugging? but they do not address this specific issue.
It is a good idea.
The only purpose of thread name is for diagnosis, so you are encouraged to name/rename threads the best way that helps you understand what's going on at runtime.
Especially for threads in a thread pool. Their identities are meaningless. It's functionally equivalent to have a new thread per task. We care only about the task names, and thread name is a convenient place to store a task name.
I would give each thread a meaningful, but not dynamically changing, name.
Storing information about which request is being processed sounds fine, but storing that in the thread name smells. You could log that information, or store it in a ThreadLocal
, or...?
精彩评论