Question

Is there a way for a Java program to detect when the operating system is about to go to sleep, or failing that, at least detecting a wake up?

The actual problem is that in a particular application a number of MySQL database operations are run in the background. In testing on a Windows machine these database transactions are interrupted after a sleep/wake-up cycle causing a ton of error conditions in the program. These errors typically look something like this:

java.net.SocketException
MESSAGE: Software caused connection abort: recv failed

If we could react to a 'will sleep soon' event we could attempt to pause background operations preempting the problem. Less ideally if we could react to a 'just woke up' event we could at least suppress the error messages.

Was it helpful?

Solution

You could detect the wakeup by periodically comparing the current system time to the previous system time.

Edit: here's an example that looks like it would help you detect when the machine is going to sleep: http://www.codeguru.com/cpp/w-p/system/messagehandling/article.php/c6907

OTHER TIPS

I know it's not exactly what you're looking for, but maybe the right answer is to try to write the code with the assumption that your sockets won't necessarily stay up. There are lots of reasons why the connection could crash, for example because the DB is taken down for maintenance, or because someone tripped over your Ethernet cable. I think you'd have similar problems with errors if someone pulled out the network cable while your app was running, and these are not unheard-of conditions, so maybe it's a better approach to try and handle those conditions gracefully.

You could just JNI or JNA to trap the sleep/wakeup events from the OS.

From Windows Power Events (MSDN), you would have to create a Window handler and a null window to receive the WM_POWERBROADCAST events. This window procedure could then call an event function in your Java code to bubble the message up.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top