user1582269
user1582269

Reputation: 305

Regarding shutdownhook understanding

I was going through shutdown hook feature of java , My analysis was ..shutdownhook allows to register a thread that will be created immediatly but started only when the JVM ends ! So it is some kind of "global jvm finalizer", and you can make useful stuff in this thread (for example shutting down java ressources like an embedded hsqldb server). This works with System.exit(), or with CTRL-C / kill -15 (but not with kill -9 on unix, of course).

Please advise more practical uses and please also if possibe an small example will help to make understanding more clear..!

Upvotes: 0

Views: 257

Answers (1)

FThompson
FThompson

Reputation: 28687

When a shutdown hook is added to a Runtime instance, it is added to a list of Threads to start upon clean termination of the JVM.

Example: Using shutdown hook to ensure that a java.awt.TrayIcon is removed from the system tray.

Runtime.getRuntime().addShutdownHook(new Thread() {
    public void run() {
        try {
            if (SystemTray.isSupported()) {
                SystemTray.getSystemTray().remove(yourTrayIcon);
            }
        } catch (Exception e) {
            // failed to remove
            e.printStackTrace();
        }
    }
});

More can be read in the offical documentation.

Upvotes: 1

Related Questions