Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should Java Thread IDs always start at 0?

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.

like image 469
pypmannetjies Avatar asked Aug 11 '09 18:08

pypmannetjies


2 Answers

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.

like image 100
John Calsbeek Avatar answered Oct 05 '22 02:10

John Calsbeek


Yes. But the thread ID is shared by whole JVM so for you application it could start from any number.

like image 27
ZZ Coder Avatar answered Oct 05 '22 02:10

ZZ Coder