Question

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

Was it helpful?

Solution

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

OTHER TIPS

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:

  • unique for a given runtime session
  • reused from session to session
  • still linked to the internal original naming policy managed by the 1.4 JVM ("Thread-1", "Thread-2", ...)

You can use getID if you are on JDK 1.5 or higher.

Is it the case that you need a consistent value for each time you run the unit tests, or is just a unique value good enough?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top