Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a good idea to dynamically change the names of processing threads in Java?

We have 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.

like image 383
victor.bronstein Avatar asked Jun 05 '11 19:06

victor.bronstein


2 Answers

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.

like image 138
irreputable Avatar answered Sep 18 '22 12:09

irreputable


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...?

like image 24
Matt Ball Avatar answered Sep 19 '22 12:09

Matt Ball