How to deal with ^ C in JVM console applications?

When the JVM ran (actually written in Scala, but I am inclined to believe that the solution will be almost the same as for Groovy, Clojure or pure Java), my console program ends with the Ctrl+ button C(or the system shutdown sequence, I don’t know is there any difference for the program), how can I make sure that external resources change by the application (databases, files, abstracted web service resources) remain in a predictable, not logically damaged state?

+5
source share
3 answers

Take a look at Runtime.addShutdownHook .

Usually you use it like this:

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

, :

, . , , , SIGKILL Unix TerminateProcess Microsoft Windows. , , , . , , - .

, , . , , Apache Commons Transaction

+10

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

Perhaps just adding a shutdown hook is all you need. But I would experience this for your situation.

+3
source

All Articles