Thread.setName(name) caveats Thread.setName(name) caveats multithreading multithreading

Thread.setName(name) caveats


If you use Log4j, there is a specific mechanism for handling this type of logging pattern, split between two classes org.apache.log4j.NDC and org.apache.log4j.MDC ('Nested and Mapped Diagnostic Contexts').

Have a browse at NDC vs MDC - Which one should I use? to see which is the best to use for your particular situation.

Here's another link which describes MDC use in a bit more practical detail: Build Flexible Logs With log4j - O'Reilly Media

Note that underlying storage mechanism MDC/NDC uses (I believe) is ThreadLocal anyway.


What are the caveats for using thread.setName() apart from those mentioned in the javadoc? How does it affect performance? The peak frequency of calling thread.setName() would be about 200 per second and average about 0.3 per second.

Performance should not be a significant issue. Thread.setName() does a security check and then copies / sets an attribute. The security check should be cheap unless your code is privileged code running in a security sandbox that forbids unprivileged calls to the Thread.setName() method.

The only other caveat I can think of is that thread names changing all of the time could be confusing if you are trying to debug threading behaviour; e.g. looking at thread dumps, etc.


I use your second approach in developed software (printserver), but threads have a long run so "setName()" don't add latency in processing.The logging phase is very good showing thread name.

I think "setName()" is a problema in two case:

  1. very short run;
  2. thread used by more actors with different id (but this is not your context, or not?).

bye.