0

Is there a reliable way to write the contents of a static object to disk when the program ends?

At the moment, I call a persist() method on the static object at the end of each main() method that uses the static object. I wonder whether this can be done automatically.

J Fabian Meier
  • 33,516
  • 10
  • 64
  • 142
  • 2
    What's a "static object"? – Kayaman May 25 '16 at 13:18
  • More concretely, I could have a public static myStoredClass which should be written to a file by myStoredClass.persist() at the end of the program (to read it back for all subsequent runs of different main methods). – J Fabian Meier May 25 '16 at 13:21
  • http://stackoverflow.com/questions/13754263/how-to-ensure-a-piece-of-code-is-run-before-exiting-a-java-application is a very similar question. – zapl May 25 '16 at 13:31

1 Answers1

2

You could add a shutdown hook, which will ensure that your code is executed when the JVM is exiting gracefully (not forcibly killed).

For more information, check the accepted answer here: Useful example of a shutdown hook in Java?

A howto can be found here: http://hellotojavaworld.blogspot.co.za/2010/11/runtimeaddshutdownhook.html

Community
  • 1
  • 1
ernest_k
  • 44,416
  • 5
  • 53
  • 99