Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deal with ^C in JVM console applications?

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?

like image 830
Ivan Avatar asked Feb 03 '12 12:02

Ivan


2 Answers

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

like image 175
Kris Avatar answered Sep 27 '22 18:09

Kris


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.
    }
});
like image 34
adarshr Avatar answered Sep 27 '22 16:09

adarshr