Does there exist and impossible/invalid value for `Thread.getId()`?

Is there any long value that cannot be returned by Thread.getId()? Having such a value would be very useful for indicating "no thread" or an unset value or whatever. I suppose I could just pick an ID at random and only have a 1 in 2^64 chance of this blowing up on me, but I'd rather not.

I could also create a thread that does nothing but hang around forever and use its ID as the invalid ID (since for all intents and purposes the thread does not exist except to provide an ID that I'm sure won't be used by another thread) - but that also seems like overkill.

Jon Skeet
people
quotationmark

One obvious option is to keep a Long instead of a long wherever you're using this. Then you can just use a null reference for "no associated thread". That's a good general approach to this problem.

However, in the specific case of threads, [Thread.getId]1 makes it easy even if you need to use a long:

Returns the identifier of this Thread. The thread ID is a positive long number generated when this thread was created. [...]

(Emphasis mine.)

So just use -1 (or any negative number) to indicate an invalid thread ID. While the "positive" here would suggest that 0 should be invalid too, I'd err on the side of caution and not rely on it - it's all too easy to write "positive" when one means "non-negative".

people

See more on this question at Stackoverflow