In some cases, most of us write things like this:
try { Thread.sleep(2000); } catch (InterruptedException e) { ; // do nothing }
Whether right or wrong, acceptable only in some test harnesses, is not my point. My point is that the same code could be written,more succinctly, as:
LockSupport.parkNanos(2000* 1000000);
is there any reason why I should favour one approach over the other.
It's fine to use Thread. sleep in that situation. The reason people discourage Thread. sleep is because it's frequently used in an ill attempt to fix a race condition, used where notification based synchronization is a much better choice etc.
ParkNanos(Int64) Disables the current thread for thread scheduling purposes, for up to the specified waiting time, unless the permit is available.
Thread sleep doesn't lose any monitors or locks current thread has acquired. Any other thread can interrupt the current thread in sleep, in that case InterruptedException is thrown.
Sleep(0) gives up CPU only to threads with equal or higher priorities.
Readability: Thread.sleep
has a pretty intuitive meaning. How would you describe (to another developer) your use of LockSupport.parkNanos
? If that description primarily consists of "I want the current thread to sleep" then surely Thread.sleep
is more descriptive.
The conciseness comes from the lack of interrupt handling - so create a wrapper method to do this if you want, which propagates the exception as a RuntimeException
. Heck, if you're creating a wrapper method, you can use either implementation, although another thread could of course unpark your "sleeping" thread in the same way as it could interrupt it...
The docs for the method parkNanos
provides the conditions in which the method can return. One of those conditions is: the call spuriously (that is, for no reason) returns. So basically it's OK to use it if you don't mind spurious wake-ups and some other Thread "unparking" the waiting thread in consideration. And of course, the comment by Jon pretty much nails the reasoning for preferring one over another.
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