简体   繁体   中英

unique id in java thread

My application uses a logging component which needs to keep track of a unique identifier for each call.

My starting point is an MDB which obviously initiates a series of methodcalls to several classes. Each class creates a new logger-object, similar to log4j, and uses this to log events to the database. And for each logger-object that gets created, a unique identifier is assigned to it. This identifier should follow the thread until the subsequent calls all return and the onMessage-method in my MDB terminates.

The problem is that during the processing of one JmsMessage, another message is received by the MDB and my IDs get mixed up.

I have been banging my head against the desk for some time now and I guess the answer is right in front of me, but have you got any ideas? How can I make sure that one "process" can log using its own ID even if another is started before the first one finishes?

Thank you in advance.

Is there a reason you can't use Message.getJMSMessageID() ?

If there is, AtomicLong.incrementAndGet() should be all it takes. Keep one static instance, and in the MDB's onMessage() method get an ID and keep it around while the message is processed (perhaps in a ThreadLocal ).

Usually you want to use the "friendly" name

String name = Thread.currentThread().getName();

However, this might no be unique or meaningful in which case you can use a unique id.

int id = Thread.currentThread().getId();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM