Java: Prepare for forced shutdown - java

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

Related

Detect when computer goes into sleep mode [duplicate]

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.

Is it possible to simulate abrupt restarts of a java application without killing the jvm?

I want to stress test application resilience and verify the data is consistent given frequent power shutdowns.
As the goal is to test persistent state only the app itself is technically not required to be stopped immediately e.g. if there is a way to detach the file system somehow, or freeze writing and make a copy of the state that would do, any way without resorting to killing the process either from inside as System.exit or a sigkill from outside.
System.exit(1); is functionally identical to what happens when the JVM receives a KILL signal from the operating system. However, ShutdownHooks will still execute.
Runtime.getRuntime().halt(1) will halt the JVM immediately, as if the operating system had killed the process without warning.
However, neither is fully equivalent to a sudden loss of power, which would also kill the operating system, possibly causing OS-buffered disk writes to be lost.

What happens to a Java program when you turn the power off?

What happens within a Java application running locally on a PC when the power is switched off?(Plug pulled from wall).
Does Java have a way of handling an event like this or is it simply wiped from memory as soon as the power is killed?
Edit: To be a bit more clear, I'm wondering if Java as any way of safely exiting an application in the last moments of an unexpected shutdown.
Java programs (like all programs) require a CPU and memory to operate instructions. Both elements are complex electrical circuits, they cannot work without electricity.
The only thing you can do to persist the state of your application, is to write information regarding that state to disc. The Google File System uses this method to ensure not too much information is lost if one of their (usually inexpensive machines) goes down.
Short of this. No there is no way Java can handle a power out.

Any Shutdown Hook when application is "Force Closed"?

Is there any way to make the program go through the shutdown hook if the user forces java to close (through the task manager or by closing the corresponding batch file).
My program currently runs and executes well, if the user closes the GUI then it goes through a set of steps to disconnect from the database. However, if the user closes the Java or the batch file (running side by side with the GUI) then the connection to the database isn't closed.
Is it possible to somehow force the connection closed and maybe even delete something from the tables? The batch file will probably not be an issue when I jar the program but the process killing still will.
Nope.
The shutdown hook will react to Ctrl+C, normal closes, user logouts, and normal system shut downs (which request a graceful shutdown of all applications).
However, if someone is force-closing the app it's assumed that that's what you actually want - immediate termination with no further notice. This question has been asked many times, and is confused by the behavior of many applications that, when they are asked to force-close, they actually take a long time to finally terminate. This is because in the OS's efforts to release all resources, some resources (especially certain I/O and/or file resources) don't let go immediately.
In testing an app that starts, and is intended to be running until a graceful shutdown (e.g. server software) you should run it at the console/command-line, and press Ctrl+C to stop the program (which will run the shutdown hook) rather than using Task Manager, or KILL -9.
Furthermore, there's nothing Java could even do about it if it wanted to. A force-close happens at the OS level, at which point it releases the memory, file and I/O handles in use, etc. Java does not (nor does any other program) have control over a force-close. At this point, the OS is taking charge.

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.

Categories

Resources