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

Dr Heinz M. Kabutz heinz at javaspecialists.eu
Mon Aug 27 05:05:36 EDT 2018


IMHO if your code breaks because Thread.sleep woke up too early or too
late, your code was incorrect to start with.  Same with wait(), which can
be subject to spurious wakeups apparently.  But even if that happens,
correct code would still work :-)

My thumb rule with wait() is to always write it in such a way that it would
also work with notifyAll(), whether you use that or notify().  If you do,
it will still work with spurious wake ups or lost races for the lock.

For time sensitive waiting, I prefer Condition.awaitMillis().

It is of course neither precise nor real-time.

Heinz

On Mon, 27 Aug 2018 at 11:38, Thorsten Goetzke via Concurrency-interest <
concurrency-interest at cs.oswego.edu> wrote:

> > 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."
> >
>
> I think in case of Thread.sleep the javadoc should be clarified so it
> explicitly contains the word "less".
> It just says "subject to the precision and accuracy of system timers and
> schedulers" which can be missunderstood as "at least sleep time + the
> jvm does it's best to reduce additional sleep time but it obviosly cant
> magically make the undlerying system more precise".
>
>
> https://docs.oracle.com/javase/10/docs/api/java/lang/Thread.html#sleep(long)
>
>
> _______________________________________________
> Concurrency-interest mailing list
> Concurrency-interest at cs.oswego.edu
> http://cs.oswego.edu/mailman/listinfo/concurrency-interest
>
-- 
Dr Heinz M. Kabutz (PhD CompSci)
Author of "The Java(tm) Specialists' Newsletter"
Sun/Oracle Java Champion
JavaOne Rockstar Speaker
http://www.javaspecialists.eu
Tel: +30 69 75 595 262
Skype: kabutz
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://cs.oswego.edu/pipermail/concurrency-interest/attachments/20180827/7aabd0e6/attachment.html>


More information about the Concurrency-interest mailing list