[concurrency-interest] Sleep time consistency compared to System.currentTimeMillis

Doug Lea dl at cs.oswego.edu
Sat Aug 25 09:57:46 EDT 2018


On 08/24/2018 05:10 AM, Thorsten Goetzke via Concurrency-interest wrote:
> Hello,
> 
> There are multiple Classes that let you wait or sleep for a specified
> amount of time. My current understanding is:
> Thread.sleep and Object.wait can wake up earlier than specified so code
> that also uses System.currentTimeMillies can break because wakeups
> happen to early.

Yes, and the JDK API specs for these methods include disclaimers,
including: "The specified amount of real time has elapsed, more or less."

> On the other side code that uses higher level Abstraction such as
> ScheduledExecutorService or CountDownLatch.await will always at least
> wait for the specified time and it will be consistent with
> System.currentTimeMillies. Is that actually correct and guaranteed


Yes, java.util.concurrent time-based API specs do not include any such
disclaimers, so you will never get a too-short wait. Delays may be
arbitrarily longer than you'd like though. Imagine millions of threads
waiting for a millisecond. Not all of them will start running after a
millisecond.

-Doug


More information about the Concurrency-interest mailing list