Thread.getId() global uniqueness question

故事扮演 提交于 2019-12-04 18:03:46

问题


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?


回答1:


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.




回答2:


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)



来源:https://stackoverflow.com/questions/591627/thread-getid-global-uniqueness-question

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!