Frage

When a JVM-ran (written in Scala actually, but I tend to believe that the solution is going to be pretty much the same for Groovy, Clojure or pure Java) console program of mine gets terminated by the user pressing Ctrl+C (or by the system shut-down sequence, I don't know if there is any difference for a program), how do I make sure the external resources the application modifies (databases, files, web service abstracted resources) are left in a predictable, non-logically-corrupt state?

War es hilfreich?

Lösung

Take a look at Runtime.addShutdownHook.

You would typically use it as so:

Runtime.addShutdownHook(new Thread() {
    public void run() {
        // do your clean up here.
    }
});

Andere Tipps

You can try to implement a shutdown hook as others pointed BUT:

In rare circumstances the virtual machine may abort, that is, stop running without shutting down cleanly. This occurs when the virtual machine is terminated externally, for example with the SIGKILL signal on Unix or the TerminateProcess call on Microsoft Windows. The virtual machine may also abort if a native method goes awry by, for example, corrupting internal data structures or attempting to access nonexistent memory. If the virtual machine aborts then no guarantee can be made about whether or not any shutdown hooks will be run.

I guess, you would have to introduce transactional context into your application I believe. For databases that's quite easy, for file system you can look into Apache Commons Transaction

You can trap this signal and close off resources. Most services do not need to be closed gracefully, however files you write to usually do.

It is possible just adding a shutdown hook is all you need. But I would test this for your situation.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top