How To Let Java Handle System Interrupts Like Ctrl+C

dimo414 picture dimo414 · Aug 4, 2009 · Viewed 8.3k times · Source

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?

Answer

Amber picture Amber · Aug 4, 2009

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:

How can I "intercept" Ctrl+C in a CLI application?