There is a console Java application which is supposed to run untill it is stopped by Ctrl+C or closing the console window. How that application can be programmed to execute a clean up code before exit?
+8
A:
You could use a Shutdown Hook.
Basically you need to create a Thread which will perform your shutdown actions, and then add it as a shutdown hook. For example:
class ShutdownHook extends Thread
{
public void run()
{
// perform shutdown actions
}
}
// Then, somewhere in your code
Runtime.getRuntime().addShutdownHook(new ShutdownHook())
Phill Sacre
2008-11-05 10:58:02
+1 - Perhaps you could elaborate with an instructive example?...
johnstok
2008-11-05 11:04:21
Example added. Thanks.
Phill Sacre
2008-11-05 11:17:58
A:
A Shutdown hook is the way to go, but be aware that there is no guarantee that the code is actually executed. JVM crashes, power failures, or a simple "kill -9" on your JVM can prevent the code from cleaning up. Therefore you must ensure that your program stays in a consistent state even if it has been aborted abruptly.
Personally, I simply use a database for all state-storage. Its transactions model makes sure that the persistent storage is in a sane state no matter what happens. They spend years making that code fool-proof, so why should I waste my time on problems already solved.