Detect when computer goes into sleep mode [duplicate] - java

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.

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

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.

Related

Java: Prepare for forced shutdown

I am making an application in Java where I want to always have the data saved to a file with minimal saving operations. In other words, whenever the app is closed or an exception is thrown, it will first attempt to save. The one problem: the POWER BUTTON. When a user holds the power button to a computer, it forces the OS to shut down. Now, how exactly do I make Java detect an incoming shut-down, or will the JVM shut the system first (therefore calling shutdown hooks)?
I summarize here what was mostly already written in the comments.
What normally happens when the user presses the power button for more than 4 seconds, is that the bios will cut power to the mainboard and all peripherals.
There is no way software (OS or user software) can react to this situation.
What may happen is that hard drives would flush any hardware buffer and park the heads in a safe position for transportation but it may as well not happen and the programmer has anyway no way to control that.
What you may react to regular system shutdown using shutdown hooks

Crystal Report java library, logon hangs forever

Our project uses Business Objects for reports. Our java webapps that launch reports go thruogh a web service we set up to handle the business rules of how we want to launch them. Works great...with one wrinkle.
BO appears to be massively unreliable. The thing frequently goes down or fails to come up after a nightly timed restart. Our Ops team has sort of gotten used to this as a fact of life.
But the part of that which impacts me, on the java team, is our webservice tries to log on to BO, and instead of timing our or erroring like it should, the BO java library hangs forever. Evidently it is connecting to a half-started BO, and never gives up.
Looking around the internet, it appears that others have experienced this, but none of the things I see suggests how to set a timeout on the logon process so that if it fails, the web service doesn't lock up forever (which in turn can cause our app server to become unstable).
The connection is pretty simple:
session = CrystalEnterprise.getSessionMgr().logon(boUserName, boPassword, boServerName, boSecurityType);
All I am looking for is some way to make sure that if BO is dead, my webservice doesn't die with it. A timeout...a way to reliably detect if BO is not started and healthy before trying to logon....something. Our BO "experts" don't seem to think there is anything they can do about BO's instability and they know even less about the java library.
Ideas?
The Java SDK does not detail how to define a timeout when calling logon. I can only assume that this means it falls back on a default network connection timeout.
However, if a connection is made but the SDK doesn't receive the required information (and keeps waiting for an answer), a network timeout will never be reached as this is an application issue, not a network issue.
Therefore, the only thorough solution would be to deal with the instabilities in your BusinessObjects platform (for which you should create a separate question and describe the issue in more detail).
If this is not an option, an alternative could be to launch the connection attempt in a separate thread and implement a timeout yourself, killing the thread when the predefined timeout is reached and optionally retrying the connection attempt several times.
Keep in mind though that while the initial logon might be successful, the instabilities described in your question could cause other issues (e.g. a different SDK call could remain hanging forever due to the same issue that caused your logon call to hang).
Again, the only good solution is to look at the root cause of your platform instabilities.

What are the possible reasons that even after successfull execution control doesnt come back to prompt?

I am running a Java Program in command prompt
The normal course is after successfully executing the program it comes back to prompt .. what are the possible reasons it will not come back to prompt after successfully executing the program
why is it not coming back to prompt after execution
usually it comes back but sometimes it doesn't...
This sounds like a race condition. Something in your application's shutdown sequence is non-deterministic, and it works or does not work depending on various platform specific (and possibly external) factors. There is probably no point figuring out what those factors are (or might be), since it won't help you fix the problem.
Only difference is in RAM hard disk capacity mine is slower.. Can it be possible reason?
These could be factors, but they are not the cause of the problem. So focus on figuring out what makes your application non-deterministic.
As others have said, without more information (and relevant code) we can only guess.
When the application has failed to shut down, get it to give you a thread dump. Or try shutting it down while it is attached to a debugger. These may allow you to get some clues as to what is going wrong.
Finally, the brute force solution is simply to have the main method (or whatever) call System.exit(0) on its way out. But beware of the possibility of files not being flushed, etc if you do that.
Because it's not finishing. If it's sometimes happening and sometimes not, my instinct is that you have some sort of race condition. Probably one of your cleanup steps is hanging if another action has or hasn't been taken.
Without source code this will be hard to debug.
There could be an active thread still running which is not in "daemon" mode. For example, if you have a Swing GUI and all of the frames are closed the Event Dispatch thread is still active so the JVM will not exit.

Detect OS Sleep and Wake Up events in Java

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.
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
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.

How to detect dataloss with Java sockets?

I have the following situation: using a "classical" Java server (using ServerSocket) I would like to detect (as rapidly as possible) when the connection with the client failed unexpectedly (ie. non-gracefully / without a FIN packet).
The way I'm simulating this is as follows:
I'm running the server on a Linux box
I connect with telnet to the box
After the connection has succeeded I add "DROP" rule in the box's firewall
What happens is that the sending blocks after ~10k of data. I don't know for how long, but I've waited more than 10 minutes on several occasions. What I've researched so far:
Socket.setSoTimeout - however this affects only reads. If there are only writes, it doesn't have an effect
Checking for errors with PrintWriter.checkError(), since PW swallows the exceptions - however it never returns true
How could I detect this error condition, or at least configure the timeout value? (either at the JVM or at the OS level)
Update: after ~20min checkError returned true on the PrintWriter (using the server JVM 1.5 on a CentOS machine). Where is this timeout value configured?
The ~20 min timeout is because of standard TCP settings in Linux. It's really not a good idea to mess with them unless you know what you're doing. I had a similar project at work, where we were testing connection loss by disconnecting the network cable and things would just hang for a long time, exactly like you're seeing. We tried messing with the following TCP settings, which made the timeout quicker, but it caused side effects in other applications where connections would be broken when they shouldn't, due to small network delays when things got busy.
net.ipv4.tcp_retries2
net.ipv4.tcp_syn_retries
If you check the man page for tcp (man tcp) you can read about what these settings mean and maybe find other settings that might apply. You can either set them directly under /proc/sys/net/ipv4 or use sysctl.conf. These two were the ones we found made the send/recv fail quicker. Try setting them both to 1 and you'll see the send call fail a lot faster. Make sure to take not of the current settings before changing them.
I will reiterate that you really shouldn't mess with these settings. They can have side effects on the OS and other applications. The best solution is like Kitson says, use a heartbeat and/or application level timeout.
Also look into how to create a non-blocking socket, so that the send call won't block like that. Although keep in mind that sending with a non-blocking socket is usually successful as long as there's room in the send buffer. That's why it takes around 10k of data before it blocks, even though you broke the connection before that.
The only sure fire way is to generate application level "checks" instead of relying on the transport level. For example, a bi-directional heartbeat message, where if either end does not get the expected message, it closes and resets the connection.

Categories

Resources