File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Threads and Synchronization and the fly likes How to get the Thread ID Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "How to get the Thread ID" Watch "How to get the Thread ID" New topic
Author

How to get the Thread ID

Shankar Shanmugam
Greenhorn

Joined: Sep 12, 2001
Posts: 23
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: shankar.s@vsnl.net<br /> "Walking on water and building IT Architecture from <br /> specification are easy if and only if both are frozen"<br />-----------------------------------------------
Jon Strayer
Ranch Hand

Joined: Dec 04, 2002
Posts: 133
No, Threads have names, not id numbers. As long as no one changes the name you could hash the name to give you a number.


Jon
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
You can use Thread's setName() method to give a thread whatever name you want, if that helps.


"I'm not back." - Bill Harding, Twister
Paulo Salgado
Ranch Hand

Joined: Jan 18, 2002
Posts: 98
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.

Hope this helps.
Peter den Haan
author
Ranch Hand

Joined: Apr 20, 2000
Posts: 3252
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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How to get the Thread ID