Hi, we are developing a API and this API needs to identify the calling thread using a Thread ID. And, this thread if should be an int values. Thats what the API design says. I would like to know whether we can obtain a unqiue thread id? Does JVM exposes such a unique int id for a thread. Thanks in advance, Shankar
Shankar Shanmugam<br />Sun Certified Programmer for Java 2 Platform<br />Sun Certified Developer for Java 2 Platform<br />Email: firstname.lastname@example.org<br /> "Walking on water and building IT Architecture from <br /> specification are easy if and only if both are frozen"<br />-----------------------------------------------
Shankar, I've seen a sample of what you want to achieve in the book Java Thread Programming by Paul Hyde. The author uses a subclass of ThreadLocal to generate a new unique Id every time a new thread executes a method to get such id. Well, rather than writing about it, let me post the author's sample. Below is the class the inherits from ThreadLocal and generates the unique id's:
And the class below, is a sample of how to use it.
Originally posted by Shankar Shanmugam: Does JVM exposes such a unique int id for a thread.
As mentioned, no. You will have to put some pretty clunky code in place to turn a Thread into a number. I would really query the design and ask what's wrong with using the Thread object itself identifier. Some might try to tell you to use Thread.hashCode(). Don't listen to them. It will actually work on 32-bit CPU architectures, but is not guaranteed to work on 64-bit or larger. - Peter