Ok we need some more info here. Are you interested in all threads or just the ones that you create (sounds like all)? Do you need the same value to be returned with each run of the unit tests or can the returned value be different each time the unit tests are run?
–
TofuBeerMar 31 '09 at 15:51

4 Answers
4

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

That is just the implementation by Sun though, it could be changed to not simply to ++ and actually be aggressive at reuse. Odds of that happening are likely low, and odds of a different implementation, say the Classpath project, using a different method is slim.
–
TofuBeerMar 31 '09 at 14:55

Classpath (isn't it dead yet) and Harmony could use a different, egregiously non-compliant implementations, but in practice that is only a theoretical possibility.
–
Tom Hawtin - tacklineMar 31 '09 at 15:06

@Tom Hawtin: But the API docs specifically state, "When a thread is terminated, this thread ID may be reused."
–
Michael Myers♦Mar 31 '09 at 15:09

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.

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