wood burning stoves
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

Runtime.addShutdownHook method ???

Vassili Vladimir
Ranch Hand

Joined: Mar 08, 2007
Posts: 1585

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: 15082

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 8 API documentation
I agree. Here's the link: http://aspose.com/file-tools
subject: Runtime.addShutdownHook method ???
It's not a secret anymore!