Why does, for example, Thread.currentThread().getId()
return a long?
Does this really need to be 64 bits? Like I'm going to ever have a machine running that number of threads!
Seriously, it's a bit of a pain since I'm writing something that keeps a track of thread identifiers along with other bits and I'd really rather not have to use such a long number, else the unique key I have to generate is enormous.
Perhaps there is a convention on the long return; like the first 48 bits are always zero. I had a dig about on the internet but didn't find anything. I hope so; does anyone know for sure?
Thanks.
This code:
private static synchronized long nextThreadID() {
return ++threadSeqNumber;
}
should give insight as to why. Essentially thread ids are assigned by a running counter, so if you don't terminate your JVM for a significant amount of time, this number would go above the long. I can only imagine that they did it to reduce the chance for collisions in long running threads.
Java applications are sand-boxed relative to other Java applications, which is way thread ID's are even likely to collide.
Threads are not meant to be unique across all application, they are only unique per application. Looking at the Thread.init
method in the source, you can find:
private static synchronized long nextThreadID() {
return ++threadSeqNumber;
}
/* For generating thread ID */
private static long threadSeqNumber;
I guess it's used to prevent a potential overflow bug. As threads get created, the number would eventually overflow. Long is just being
9223372036854775807(Max long value) - 2147483647(Max int value) = 9.223372e+18
a bit more safe:)
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