Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread.getId() global uniqueness question

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?

like image 308
Ben S Avatar asked Feb 26 '09 17:02

Ben S


People also ask

Are thread ID unique?

Yes, thread ID's and Process ID's on Windows are allocated from the same pool, so they will be unique.

Is Java thread ID unique?

The thread ID is unique and remains unchanged during its lifetime. When a thread is terminated, this thread ID may be reused. Java allows concurrent execution of different parts of a program with the help of threads.

What is the return type of getId ()?

The getId() method is used to return the thread identifier. The thread ID is a unique positive number which was generated at the time of thread creation. The thread ID remains unchanged during its lifetime.

Are thread IDs reused?

Because thread IDs can be reused without notice as threads are created and destroyed, this value is more reliable than the value returned by the GetCurrentThreadId function.


1 Answers

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.

like image 124
Michael Myers Avatar answered Nov 10 '22 10:11

Michael Myers