CountDownLatch 是否受到虚假唤醒的影响?
Is CountDownLatch affected by spurious wakeups?
wait/notify 和 lock/condition 等并发管理机制似乎受到 spurious wakeups 的影响。开发人员通过重新检查条件是否确实发生了变化来应对这些意外唤醒。
谈到 CountDownLatch,虚假唤醒是个问题吗?
CountDownLatch#await()
的 javadoc 指出
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.
休眠 意味着该方法不会 return。换句话说,尽管可能会发生虚假唤醒,但它不会导致 await
方法变为 return。
您可以查看 implementation 以了解这是如何完成的,但简而言之,这是循环和 "waiting" 的典型技巧(通过 LockSuport#park
或 Object#wait
受虚假唤醒影响)直到满足条件。
When it comes to CountDownLatch
, are spurious wakeups an issue?
没有
Object.wait/Condition.await
方法受制于 "spurious wakeups"。
CountDownLatch
中的 await
方法将等到
- 由于调用了 countDown() 方法,计数达到零;
或其他某个线程中断了当前线程;或指定的
等待时间结束。
因此即使发生虚假唤醒,由于计数未达到,也不会return。
所以 CountDownLatch
、CyclicBarrier
等同步器不受虚假唤醒的影响。
wait/notify 和 lock/condition 等并发管理机制似乎受到 spurious wakeups 的影响。开发人员通过重新检查条件是否确实发生了变化来应对这些意外唤醒。
谈到 CountDownLatch,虚假唤醒是个问题吗?
CountDownLatch#await()
的 javadoc 指出
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.
休眠 意味着该方法不会 return。换句话说,尽管可能会发生虚假唤醒,但它不会导致 await
方法变为 return。
您可以查看 implementation 以了解这是如何完成的,但简而言之,这是循环和 "waiting" 的典型技巧(通过 LockSuport#park
或 Object#wait
受虚假唤醒影响)直到满足条件。
When it comes to
CountDownLatch
, are spurious wakeups an issue?
没有
Object.wait/Condition.await
方法受制于 "spurious wakeups"。
CountDownLatch
中的 await
方法将等到
- 由于调用了 countDown() 方法,计数达到零; 或其他某个线程中断了当前线程;或指定的 等待时间结束。
因此即使发生虚假唤醒,由于计数未达到,也不会return。
所以 CountDownLatch
、CyclicBarrier
等同步器不受虚假唤醒的影响。