9

Concurrency management mechanisms such as wait/notify and lock/condition seem to be affected by spurious wakeups. Developers cater for those unexpected wakeups by re-checking that the condition has indeed changed.

When it comes to CountDownLatch, are spurious wakeups an issue?

Fidel
  • 7,027
  • 11
  • 57
  • 81
  • Spurious wakeups are a _documented behavior_ of wait/notify. They are _not_ documented for CountDownLatch. If a CountDownLatch behaves in an undocumented way, that would be a bug. That is to say, if you implement CountDownLatch using wait/notify, then it is up to you to correctly handle a spurious wakeup, and not pass the buck to your client. – Solomon Slow Jul 22 '15 at 22:13

2 Answers2

14

The javadoc of CountDownLatch#await() states

If the current count is greater than zero then the current thread becomes disabled for thread scheduling purposes and lies dormant until one of two things happen:

  • The count reaches zero due to invocations of the countDown() method; or
  • Some other thread interrupts the current thread.

dormant meaning the method won't return. In other words, though a spurious wakeup can occur, it won't cause the await method to return.

You can look at the implementation to see how this is done exactly, but, in brief, it's the typical trick of looping and "waiting" (through LockSuport#park or Object#wait which are affected by spurious wakeups) until a condition is met.

When it comes to CountDownLatch, are spurious wakeups an issue?

No.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
4

The Object.wait/Condition.await methods are subject to "spurious wakeups".

The await method in CountDownLatch will wait until

  • The count reaches zero due to invocations of the countDown() method; or Some other thread interrupts the current thread; or The specified waiting time elapses.

So evenif spurious wakeup occurs, since the count has not reached,it wont return.

So the synchronizers like CountDownLatch, CyclicBarrier etc are not subject to spurious wakeups.

Renjith
  • 3,274
  • 19
  • 39