views:

641

answers:

3

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.

+5  A: 

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

rob
Pity it can't be done without JNI but the link seems like a good start.
Alexander Ljungberg
Yes, JNI can be a pain to develop and debug. We've found the key is to keep as much of the logic as possible in Java, and just use JNI as a bridge to make low-level calls to the C API.
rob
+2  A: 

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.

jprete
If the database does crash or someone pulls a cable I think error messages would actually be in order!
Alexander Ljungberg
Not if the request was recoverable. Sometimes they are, sometimes they aren't. Sometimes it's transient, such that the user never notices, but the system itself does. You should be able to handle that event.
Chris Kaminski
I used C3PO to do exactly this, its able to validate connections before returning them the the app from the pool.
Simon Gibbs
+1  A: 

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.

Chris Kaminski