views:

260

answers:

2

I have a java program which creates a lock file to ensure that no other executions run at the same time as it. If the program runs it creates the file, and upon exit, either successful or via an exception, the file is removed. But if the user hits Ctrl+C, closes the terminal, or in some other way interrupts execution, the file is not deleted. Is there any way to detect this interrupt command and ensure that the file is deleted in this case as well?

+2  A: 

You might want to look into shutdown hooks.

Also, this is probably a duplicate or near-duplicate of this previous SO question from a day or two ago:

http://stackoverflow.com/questions/1216172/java-how-could-i-intercept-ctrlc-in-a-cli-application/1216186#1216186

Amber
Do shutdown hooks even run when the JVM is terminated abnormally? I would doubt it.
Michael Myers
@mmyers, that depends upon your definition of abnormal. :) Ctrl-C will generally trigger them. Closing the terminal generally does not.
jsight
There's no 100% foolproof way to delete such lockfiles. Timestamping them can help, but it comes at the cost of having to do that disk write every few seconds. A lot of programs just search for a lockfile when starting up and prompt the user about it.
Amber
Yeah, we use shutdown hooks for a similar problem, and they seem to execute on almost all terminations under java 6.
aperkins
+1  A: 

The only good way to deal with this is to timestamp your log file, and update the logfile with a new timestamp every few seconds. File.deleteOnExit will help, but no method is foolproof (what happens when someone just pulls the power cord?).

If you write a timestamp, then you can check for a valid timestamp (recently written) and overwrite the log file if it is too badly out of date. That way a stale lockfile won't get in the way of the user.

jsight
Ok thank you, that's what I suspected.
dimo414