4

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

Alex K
  • 73
  • 1
  • 5
  • In theory, hibernation freezes the status of the disk, the memory and the processor and saves them securely. Meaning, once you turn on your laptop after returning from hibernation, it resumes back to where you left it off. No process or thread runs in the background during the time period. – Arihant Bansal Oct 18 '18 at 15:14

1 Answers1

3

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.

apangin
  • 92,924
  • 10
  • 193
  • 247
  • I would try repeatedly sleeping for 1 minute (or less) until the time has been reached on the wall clock. +1 – Peter Lawrey Oct 18 '18 at 18:40
  • I just tried this with Java 1.8.0_202 on Windows 10 and indeed, the sleep target time was missed by about as much time as it took to hibernate the PC, wait a while, and dehibernate it. – Dreamspace President Jul 18 '19 at 08:06