Search code examples
javaeventsexitshutdown

Java - catch PC is turning off event, or equivalent


I created a software which edits some XML files. When a file is opened a lock file is generated to avoid having multiple users editing the file at the same moment.

I would like now to be able to delete such a lock if someone turns the PC off. (The application runs on both Linux and Windows.)

Is there any common signal which is passed to the Virtual machine when attempting to close the current section?

Cheers,
Ste


Solution

  • You could try to add a shutdown hook:

    final Thread mainThread = Thread.currentThread();
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            // remove lock file...
        }
    });
    

    In this case the code in the run-method will be executed before termination of the JVM. (Unless the JVM is killed with something like kill -9 31337.)

    Related question: