Warnings Thread.setName (name)

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

I want to register the client ID in all logging statements for this client. The problem is that I do not want to change the method signatures just to pass the client identifier.

The solutions I was thinking about:

  • Using ThreadLocal to store client value.
  • In run (), I can set the client ID to Thread using Thread.currentThread (). setName (clientId);

First you need to work. But I like the second option, because a. I can find client id from debugger b. The log library can be configured to display the name of the stream. Therefore, no changes will be required for journal operators, and this will also work for journals within libraries.

What are the caveats for using thread.setName () other than those specified in javadoc? How does this affect performance? The peak frequency of a call to thread.setName () will be about 200 per second and an average of about 0.3 per second.

+5
source share
3 answers

Log4j, , org.apache.log4j.NDC org.apache.log4j.MDC ( " " ).

NDC vs MDC - ?, , .

, MDC : log4j - O'Reilly Media

, MDC/NDC ( ) ThreadLocal .

+3

thread.setName(), , javadoc? ? thread.setName() 200 0,3 .

. Thread.setName() , / . , , , Thread.setName().

, , , , , , ; ..

+2

I use your second approach in the developed software (printserver), but the streams have a long run, so "setName ()" does not add latency during processing. The registration phase is very good, showing the name of the stream.

I think "setName ()" is a problem in two cases:

  • very short mileage;
  • stream used by other participants with different identifiers (but is this not your context or not?).

bye.

+1
source

All Articles