ClassicMoj
ClassicMoj

Reputation: 23

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.

Upvotes: 0

Views: 5912

Answers (2)

Michael Borgwardt
Michael Borgwardt

Reputation: 346290

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).

Upvotes: 2

Peter Lawrey
Peter Lawrey

Reputation: 533500

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();

Upvotes: 1

Related Questions