In Java 1.4, is there any better way of getting a Thread's ID than using Thread.getName()
?
I mean, getName()
in unit tests returns something like "Thread-1"
, but in WebLogic 10 I get "[ACTIVE] ExecuteThread: '1' for queue: 'weblogic.kernel.Default (self-tuning)'.xml"
.
The thread ID is unique and remains unchanged during its lifetime. When a thread is terminated, this thread ID may be reused. Java allows concurrent execution of different parts of a program with the help of threads.
currentThread() method returns a reference to the currently executing thread object.
currentThread() is a static method , returns a reference to the currently executing thread object. After getting the reference of the current thread , we will call the getId() method on Thread class. getId() will return the unique identifier of current thread which is a positive long value.
The current thread is the currently executing thread object in Java. The method currentThread() of the Thread class can be used to obtain the current thread. This method requires no parameters.
Thread.getId (it can theoretically overflow, but it is defined not to and in practice will not).
1.5 is going through its End of Service Life period now, but if you are using old dusty-decks 1.4, then you can implement your own with ThreadLocal
. (Note, don't follow the Java SE 6 API docs too closely!)
Why do you need this? Because depending on your answer, there are several approaches.
First, understand that a thread's name is not guaranteed to be unique. Nor is identity hashcode.
If you truly want to associate a unique ID to a thread, you're going to need to do it yourself. Probably using an IdentityHashMap. However, that will introduce a strong reference that you don't want to have hanging around in a production app.
Edit: TofuBeer has solution that's probably better, although the docs note that thread IDs can be reused.
As mentioned in "Thread.getId() global uniqueness question" SO question, and confirmed by the source code of Thread.java:
/* For generating thread ID */
private static long threadSeqNumber;
/* Set thread ID */
tid = nextThreadID();
private static synchronized long nextThreadID() {
return ++threadSeqNumber;
}
The thread id is very simple to implement yourself if your are still in java1.4.
However this implementation means a given thread will not have the same id when you are running your program several times.
So depending on what you need, you may have to implement a naming policy which is both:
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