15

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?

Ben S
  • 68,394
  • 30
  • 171
  • 212

2 Answers2

25

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;

threadSeqNumber is initialized with 0 (default long value), so the first value returned by nextThreadID is 1.

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

Art
  • 2,235
  • 18
  • 34
Michael Myers
  • 188,989
  • 46
  • 291
  • 292
11

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
  • 25,520
  • 24
  • 79
  • 114
  • Yeah, I think it's unlikely that any existing system can run 9223372036854775807 threads. :) – Michael Myers Feb 26 '09 at 17:53
  • 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 Feb 26 '09 at 17:55
  • Spawning a new Thread every millisecond would take 292 277.266 millenia to overflow. – Ben S Feb 26 '09 at 17:56
  • 8
    Are you insinuating that the JVM isn't sufficiently robust to live 292,277 millenia? :P – Jared Feb 26 '09 at 18:11
  • by the time that many threads are created, it's probably considered ok to start counting at 0 again! – matt b Feb 26 '09 at 19:12
  • But it doesn't start counting at 0 again (unless you restart the JVM)....there is no if(counter == Integer.MAX_VALUE) check. – Jared Feb 26 '09 at 19:34