1

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

aioobe
  • 413,195
  • 112
  • 811
  • 826
Stefano
  • 3,981
  • 8
  • 36
  • 66

2 Answers2

2

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:

Community
  • 1
  • 1
aioobe
  • 413,195
  • 112
  • 811
  • 826
  • Little problem... since i am creatig another thred i guess only static methon can be called. I have instad a mathod removeLocksOnExit(); in the main class which i would like to refere. Do you know what could i do in this case? – Stefano Aug 31 '11 at 08:59
  • No problems calling non-static methods from other threads... don't know where you got that from... – aioobe Aug 31 '11 at 10:13
  • i posted it on another question.. just to make it more clear. here the link: – Stefano Aug 31 '11 at 12:00
  • http://stackoverflow.com/questions/7256620/java-call-a-non-static-method-from-shutdownhook – Stefano Aug 31 '11 at 12:01
  • The event is not triggered. do i have to add anything else? – Stefano Aug 31 '11 at 13:51
0

Standard Runtime.addShutdownHook(...)

More advanced technique using JNI, How do I get my Java application to shutdown nicely in windows?

Community
  • 1
  • 1