Search code examples
javascalaconsolejvmreliability

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?


Solution

  • 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.
        }
    });