Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I just fail to understand why must one use Runtime.addShutdownHook. If you want to do some cleanup when the jvm exits, why not just overload the finalize method of the daemon class. What is the advantage of using shutdown hook over finalize method.

Also there is a deprecated function runFinalizersOnExit. If I set it to false, I believe finalizers won't run. This contradicts the java guarantee that finalizers always run before garbage collections.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
390 views
Welcome To Ask or Share your Answers For Others

1 Answer

There is no guarantee that a finalizer will ever run. finalize() is called when the object is garbage collected. But the garbage collector may not collect anything when the program runs.

Shutdown hooks by contrast are run when the jvm exits normally. so even that isn't 100% guarantee either but it's pretty close. There are only a few edge cases where a shutdown hook doesn't run.

EDIT I looked up the edge cases where a shutdown hook is not executed

Shutdown hook IS executed:

  • When all of JVM threads have completed execution
  • Because of call to System.exit()
  • Because user hit CNTRL-C
  • System level shutdown or User Log-Off

Shutdown hook IS NOT executed:

  • If the VM crashes due to an error in native code then no guarantee can be made about whether or not the hooks will be run.
  • If JVM is killed using -kill command on Linux or Terminate Process on windows, then JVM exits instantly

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...