File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes Runtime.addShutdownHook method ??? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Runtime.addShutdownHook method ???" Watch "Runtime.addShutdownHook method ???" New topic
Author

Runtime.addShutdownHook method ???

Vassili Vladimir
Ranch Hand

Joined: Mar 08, 2007
Posts: 1585
Hi,

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

Thanks ...


Vassili ...
SCJP 5.0, SCWCD 1.4, SCJA 1.0
Jan van Mansum
Ranch Hand

Joined: Oct 19, 2007
Posts: 74
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 ]

SCJP 1.4, SCWCD 1.4
Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Posts: 1970
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.


Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
Vassili Vladimir
Ranch Hand

Joined: Mar 08, 2007
Posts: 1585
Thank you ranchers
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14146
    
  18

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.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Runtime.addShutdownHook method ???