I am working on a mutual exclusion assignment, but when I started I noticed my application's thread ID's start at 9. It doesn't change when I compile and execute it again. Is there some problem I'm missing, or can Java Thread IDs start at an arbitrary number? This question is related.
For those interested, here is a class from Herlihy & Shavit's "The Art of Multiprocessor Programming" for numbering threads:
public class ThreadID {
private static volatile int nextID = 0;
private static class ThreadLocalID extends ThreadLocal<Integer> {
protected synchronized Integer initialValue() {
return nextID++;
}
}
private static ThreadLocalID threadID = new ThreadLocalID();
public static int get() {
return threadID.get();
}
public static void set(int index) {
threadID.set(index);
}
}
You can then call
ThreadID.get();
which will automatically increment numbers and always start at 1.
From the Thread#getId()
documentation:
Returns the identifier of this Thread. The thread ID is a positive long 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.
Nothing indicates that it is guaranteed will start at 0. I would guess that, internally, Java makes several Thread objects before the first one that you create, and thus the thread IDs 0–8 are already occupied. However, nothing in the documentation guarantees that this number will be in any way sequential (though that's how it is current implemented), so you should not depend on that.
Yes. But the thread ID is shared by whole JVM so for you application it could start from any number.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With