Alex K
Alex K

Reputation: 73

How does Java Calculate Sleep Time when PC Goes into Hibernate Mode?

I wrote a Java program that executes some function and is expected to sleep for 12 hours (via TimeUnit.HOURS.sleep(12) ) and then continue performing another function.

I mistakenly left my laptop on overnight without being connected to power source and my laptop went into hibernate mode. This morning I awoke computer from hibernate mode and my program is running as before.

However, right now it is more than 12 hours since the the initial TimeUnit.HOURS.sleep(12) was called and the code (i.e, the second function) did not execute.

Does this mean I now have to wait an additional 12 hours (starting from when I woke laptop) before it executes my desired code? (I cannot stop my program right now to test this because I'm then guaranteeing my function won't execute even after an additional 12 hrs since it relies on the output of first function which relies on real time data)

I found a similar thread on SO related to C but nothing about Java.

Based on one thread I read program compares two time stamps when determining sleep time but certainly this can't be the case otherwise my code would have executed already. So how does thread.sleep() work under the hood?

Thanks

Upvotes: 4

Views: 772

Answers (1)

apangin
apangin

Reputation: 98610

Thread.sleep implementation is obviously platform dependent.

HotSpot JVM calls WaitForMultipleObjects on Windows and pthread_cond_timedwait with CLOCK_MONOTONIC on all POSIX operating systems. Neither Windows nor Linux API accounts time when the system is suspended.

Basically Thread.sleep was never designed to work across hibernation. For more information see the discussion of JDK-8146730 and JDK-8146527.

Upvotes: 4

Related Questions