Zo72
Zo72

Reputation: 15345

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.

Upvotes: 48

Views: 24550

Answers (3)

Sanjay T. Sharma
Sanjay T. Sharma

Reputation: 23238

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.

Upvotes: 23

Jon Skeet
Jon Skeet

Reputation: 1503080

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

Upvotes: 22

Caffeinated
Caffeinated

Reputation: 12484

LockSupport has a much more limited application, and does not support Exception handling. If you have to only lock a single thread, it is OK.

From the API:

these methods are designed to be used as tools for creating higher-level synchronization utilities, and are not in themselves useful for most concurrency control applications.

Upvotes: 1

Related Questions