How to deal with ^C in JVM console applications?
Asked Answered
G

3

6

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?

Garden answered 3/2, 2012 at 12:3 Comment(0)
R
7

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.
    }
});
Ragwort answered 3/2, 2012 at 12:6 Comment(0)
B
10

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

Bakker answered 3/2, 2012 at 12:11 Comment(1)
+1 also the only way to secure a program against blackout and system crash.Bougie
R
7

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.
    }
});
Ragwort answered 3/2, 2012 at 12:6 Comment(0)
D
3

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.

Dennie answered 3/2, 2012 at 12:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.