Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: LockSupport.parkNanos vs Thread.sleep(...)

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.

like image 255
Zo72 Avatar asked May 01 '12 12:05

Zo72


People also ask

Is it good to use thread sleep in Java?

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.

What is ParkNanos?

ParkNanos(Int64) Disables the current thread for thread scheduling purposes, for up to the specified waiting time, unless the permit is available.

Does thread sleep sleep all threads?

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.

What does thread sleep 0 do in Java?

Sleep(0) gives up CPU only to threads with equal or higher priorities.


2 Answers

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...

like image 119
Jon Skeet Avatar answered Sep 18 '22 04:09

Jon Skeet


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.

like image 29
Sanjay T. Sharma Avatar answered Sep 19 '22 04:09

Sanjay T. Sharma