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)?
Asked
Active
Viewed 295 times
0
-
1That button operates on the hardware level, so... no. – John Dvorak Nov 29 '15 at 02:39
-
@JanDvorak Alright. Thanks for the comment! – hyper-neutrino Nov 29 '15 at 02:46
-
If the OS is shut down normally while the application is still running, you can actually make use of a shutdown hook. Take a look at [shutdown hooks](http://java.sun.com/javase/6/docs/api/java/lang/Runtime.html#addShutdownHook%28java.lang.Thread%29). But yeah like @Jan said, nothing you can do about power loss. – Ken Slade Nov 29 '15 at 02:58
-
Here is a way you can put a shutdown hook for your application: `Runtime.getRuntime().addShutdownHook(new Thread() { ... } `. In case of "power off" it will not be triggered so I can suggest you to save your data on a regular basis using some scheduler. – Stephen L. Nov 29 '15 at 02:58
-
The other thing you may not like: killing applications also doesn't trigger shutdown hooks. But at least data in the write buffer of a disk isn't lost. Your unflushed application level buffers though are. – zapl Nov 29 '15 at 03:02
-
All very useful information. Thanks! – hyper-neutrino Nov 30 '15 at 01:58
1 Answers
0
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

cosenmarco
- 125
- 9