Detect OS sleep and wake events in Java

Is there a way for a Java program to detect when the operating system is about to fall asleep, or if it fails, at least detects an awakening?

The real problem is that in a particular application in the background, several operations are performed with the MySQL database. When testing on a Windows machine, these database transactions are interrupted after a sleep / wake cycle, which causes a lot of errors in the program. These errors usually look something like this:

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

If we could respond to the โ€œwill sleep soonโ€ event, we can try to suspend background operations, surpassing the problem. Less than ideal, if we could respond to the โ€œjust wake upโ€ event, we could at least suppress error messages.

+6
java mysql sleep database-connection
source share
3 answers

You can detect awakening by periodically comparing the current system time with the previous system time.

Edit: here is an example that seems to help you determine when the machine will sleep: http://www.codeguru.com/cpp/wp/system/messagehandling/article.php/c6907

+7
source share

I know that this is not exactly what you are looking for, but perhaps the correct answer is trying to write code with the assumption that your sockets will not necessarily remain. There are many reasons why a connection failure may occur, for example, because the database is being removed for maintenance or because someone has tripped on your Ethernet cable. I think you would have similar problems with errors if someone pulled out the network cable while your application was running, and these are not unheard of conditions, so maybe this is the best approach to try to handle these conditions gracefully.

+2
source share

You could just JNI or JNA catch sleep / wake events from the OS.

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

+2
source share

All Articles