Is Java Thread Getid() Thread-safe?
As the question title says, is Thread.getId() thread-safe? I recently had a problem whilst multithreading and the solution was to remove the getId() call as it was making the threa
Solution 1:
Yes, it's entirely thread-safe. The full implementation in JDK8 is:
publiclonggetId() {
return tid;
}
tid
is initialized once during construction of the Thread
object and never changed afterward.
If there was a problem in your code that removing it solved, it was what you were doing with the ID once you had it, not getting the ID.
Solution 2:
short answer: yes,
long answer: thread safe means protecting against race condition
/**
* Returns the identifier of this Thread. The thread ID is a positive
* <tt>long</tt> number generated when this thread was created.
* The thread ID is unique and remains unchanged during its lifetime.
* When a thread is terminated, this thread ID may be reused.
*
* @return this thread's ID.
* @since 1.5
*/publiclonggetId() {
return tid;
}
as you see the method is not synchronized, and the tid
is private and not final declared, but the tid
is set in the private method init
and is never changing after that, that makes the value of tid
immutable making it as well thread-safe
Post a Comment for "Is Java Thread Getid() Thread-safe?"