Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread.setName(name) caveats

I have a multi threaded client server application which uses Sockets. When a new connection is found, further execution is transferred to a new thread using the new Executors thread pool.

I want to log the client id in all logging statements for that client. The problem is that I don't want to modify method signatures just to pass the client id.

The solutions that I thought of are:

  1. Using ThreadLocal to hold client value.
  2. In run(), I can set the client id into Thread using Thread.currentThread().setName(clientId);

First one should work. But I like second option because a. I can find the client id from the debugger b. The logger library can be configured to show thread name. So no changes would be required to the log statements and it would also work for loggers inside libraries.

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.

like image 328
Dojo Avatar asked Apr 03 '11 22:04

Dojo


2 Answers

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.

like image 177
rhu Avatar answered Oct 10 '22 01:10

rhu


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.

like image 20
Stephen C Avatar answered Oct 10 '22 00:10

Stephen C