• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Runtime.addShutdownHook method ???

 
Vassili Vladimir
Ranch Hand
Posts: 1585
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Can anybody please explain what does the addShutdownHook method exactly do ? What is its purpose ?

Thanks ...
 
Jan van Mansum
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think the API description is fairly clear. It registers a thread that will be started when the VM shuts down. It gives you an opportunity to do some clean-up before your program terminates.
[ November 05, 2007: Message edited by: Jan van Mansum ]
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Shutdown hooks can be useful, but should not be overused, as they are a bit arcane and non-obvious.

People often use shutdown hooks to get something done after some random piece of code does System.exit(). However, it is often better to avoid using System.exit() altogether, or at least to restrict its use to a single place in the whole application.

System.exit() is a generally evil thing to do, in anything except a throw-away piece of utility code. It kills the whole JVM process, regardless of what other threads may be doing, and it is rare that you really know what other threads are doing, and hence whether it is actually appropriate to kill the JVM.

Much better to organise all your threads to terminate cleanly, when they have done their work, or when they receive some application-wide shutdown signal. If you organise your application like this, you can likely code shutdown procedures in ordinary Java code, rather than needing nasty shutdown hooks.
 
Vassili Vladimir
Ranch Hand
Posts: 1585
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you ranchers
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15448
42
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In addition to what Peter said: There's no real guarantee that your shutdown hooks are executed if the program terminates. Someone could kill the Java process and in that case your shutdown hook will not be executed.

So shutdown hook methods are really not that useful, because you can't count on them to be always executed before the JVM stops.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic