0

Assume I have a daemon-style Java program (one that repeatedly executes a code block forever until terminated). I have code in it to periodically check for the presence of a file, and if present, delete the file and gracefully shut the program down.

To shut down the program, rather than killing its process, I would simply touch the file and wait for the program to shut down (and for the file to disappear).

  • Is this a good practice or bad practice? What are the reasons?
  • What other ways can the graceful shut down of a Java program be implemented?

Note: I already saw this question, however none of the answers satisfy the questions above.

Community
  • 1
  • 1
ADTC
  • 8,999
  • 5
  • 68
  • 93
  • 2
    Have you considered using signals? "kill" is a signal to a process, if you write signal handlers, you can communicate with the process using them. See this link for more info: http://goo.gl/PI0wfF . IMO, the question you linked in your question **does** answer your question about how to shut down a program gracefully. – Reut Sharabani Apr 17 '14 at 10:21
  • `kill`ing a process is nothing bad, it is more something like: "Would you be so kind to shut yourself down?". (-9 is bad!) – Absurd-Mind Apr 17 '14 at 10:35
  • I don't see how your question is different from the linked question.. – Ishtar Apr 17 '14 at 11:21
  • @Ishtar there are numerous answers in the linked question but none talk about the merits and demerits of each method to achieve this. – ADTC Apr 17 '14 at 12:19
  • There is only one way to gracefully exit, that is to clean up just before terminating: addShutdownhook. If you have to exit when a file exists, sure just call System.exit. – Ishtar Apr 17 '14 at 17:47

1 Answers1

1

What if the process crashes? Now the file exists and the program will never start up again?
I've seen this mechanism used before, and that's always a weak point.

jwenting
  • 5,505
  • 2
  • 25
  • 30
  • The file can be deleted when the program is started up. Or if the program is designed to "consume" the file, it will be deleted on a first start up that fails, so a second start up will go fine. – ADTC Apr 17 '14 at 12:16
  • @ADTC nice in theory, but often such things are designed as a crude means of locking the system against having multiple instances running. Far better to just listen for a kill signal. – jwenting Apr 18 '14 at 06:27