• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to get the Thread ID

 
Shankar Shanmugam
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Jon Strayer
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can use Thread's setName() method to give a thread whatever name you want, if that helps.
 
Paulo Salgado
Ranch Hand
Posts: 98
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic