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:
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With