views:

483

answers:

2

If multiple Java applications are running on a system, is each Thread ID unique relative to all other Java threads, regardless of what application they are running in?

Java applications are supposed to be sand-boxed relative to other Java applications so I thought it might be possible for Thread IDs to collide.

If the Thread IDs are unique across all applications, won't that leak some (although very minor) information about other applications on the system? Such as how many threads have started in other applications, or even if other Java applications are running at all?

+10  A: 

Well, let me check the source.

In the Thread's init method (which is called by every constructor):

/* Set thread ID */
tid = nextThreadID();

In nextThreadID():

private static synchronized long nextThreadID() {
    return ++threadSeqNumber;
}

And:

/* For generating thread ID */
private static long threadSeqNumber;

It is never set, and thus defaults to 0.

So apparently thread ID numbers always start at 0 and increment by 1. In other words, the answer to your question is that they are not globally unique.

Michael Myers
+2  A: 

According to the JDK source, a thread ID is unique in a given JVM - in fact, it's simply implemented as a running sequence.

Here's the nextThreadID() method from 1.6.0_10:

private static synchronized long nextThreadID() {
    return ++threadSeqNumber;
}

(there's probably actually a long overflow bug in there, presumably it's never actually happened)

Jared
Yeah, I think it's unlikely that any existing system can run 9223372036854775807 threads. :)
Michael Myers
It doesn't have to run them simultaneously...suppose there is a system that creates a new thread every second (obviously it should be thread pooling, but suppose it isn't.) That's only 292471208677 years of continuous running :P
Jared
Spawning a new Thread every millisecond would take 292 277.266 millenia to overflow.
Ben S
Are you insinuating that the JVM isn't sufficiently robust to live 292,277 millenia? :P
Jared
Not if we can create a Thread every 0.99999 ms.
Tom Hawtin - tackline
by the time that many threads are created, it's probably considered ok to start counting at 0 again!
matt b
But it doesn't start counting at 0 again (unless you restart the JVM)....there is no if(counter == Integer.MAX_VALUE) check.
Jared