-1

i wanna create a java application that must perform some essential action (closing of file objects successfully or any other task) before it is terminated by the user using task manager or before the system is logged off (or shut down) by the user.

Is it possible in java????

Thanks in advance....

Ajeet
  • 11
  • 2

1 Answers1

2

You can implant shutdown hook in JVM - see this example: http://www.crazysquirrel.com/computing/java/basics/java-shutdown-hooks.jspx. Though it may not work in some cases like system crash, someone pulling the server plug etc. :-)

========================

Update

Here is relevant extract from Runtime API about your scenarios:

=> Logoff and shutdown should trigger the hook properly

The Java virtual machine shuts down in response to two kinds of events:

The program exits normally, when the last non-daemon thread exits or when the exit (equivalently, System.exit) method is invoked, or

The virtual machine is terminated in response to a user interrupt, such as typing ^C, or a system-wide event, such as user logoff or system shutdown.

=> Task Manager may not - and that's why you are not seeing your print statement

In rare circumstances the virtual machine may abort, that is, stop running without shutting down cleanly. This occurs when the virtual machine is terminated externally, for example with the SIGKILL signal on Unix or the TerminateProcess call on Microsoft Windows. The virtual machine may also abort if a native method goes awry by, for example, corrupting internal data structures or attempting to access nonexistent memory. If the virtual machine aborts then no guarantee can be made about whether or not any shutdown hooks will be run.

===================================================================

I made the following changes to that example code and it works:

  1. Placed a fake pause to keep JVM alive long enough for you to trigger Windows logoff
  2. Created a file on C drive (make change accordingly) so I can inspect the result when I log back in

Try it out...

package org.helios.util;

import java.io.BufferedWriter;
import java.io.FileWriter;

public class ShutdownHook {

    public static void main(String[] args) {
        Hook hook = new Hook();
        System.out.println("Running Main Application...");
        Runtime.getRuntime().addShutdownHook(hook);
        for (int i = 0; i < 50; i++) {
            //Pause for 4 seconds
            try {
                Thread.sleep(4000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Going back to sleep");
        }
        System.out.println("Normal Exit...");
    }

    private static class Hook extends Thread {
        public void run() {
            try {
                FileWriter fstream = new FileWriter("c:\\out.txt");
                BufferedWriter out = new BufferedWriter(fstream);
                out.write("JVM Shutting down");
                out.close();
            } catch (Exception e) {
                System.err.println("Error: " + e.getMessage());
            }
        }
    }
}
helios
  • 2,603
  • 4
  • 21
  • 26
  • +1 though, ideally, you would include a simple example of a shutdown hook in your answer. – ig0774 Jul 27 '11 at 19:14
  • Thanks,but i already try shutdownhook but it does not work.I write a java code ,quite similar to the code as provided in your suggested link ,but when i run it,and terminate it from task manager then the code in run() method is not execute.In run method i give a print statement but it is not displayed in cmd screen if i terminate the process from task manager.Is there is any problem ,should shutdownhook need some special conditions to work. Plzzz reply – Ajeet Jul 28 '11 at 19:03
  • See updates above...To summarize, you wouldn't be able to do much in case your JVM is terminated using Task Manager. You could detect whether your application was shutdown abnormally using the techniques mentioned here: http://stackoverflow.com/questions/2040570/catch-when-java-process-has-been-terminated. But again, it will just indicate about your app being terminated, but you wouldn't be able to do anything as your JVM process would be long gone! – helios Jul 28 '11 at 20:25
  • But it is also not working with Log Off and ShutDown,what can i do now.Is there is any way by which ShutDown Hook handles the SIGKILL Signal or any alternative to ShutDown Hook.Thanks for reply...... – Ajeet Jul 29 '11 at 08:22
  • try the updated code in my answer - it works during Windows logoff. Didn't test it for Shutdown though it should work as well. – helios Jul 29 '11 at 20:16
  • Thanks for reply again but it's not working,i also added a fake pause using while loop on previous example so that i can log off window & i also tried your new code ,but both are not working.I also try many other examples but all are unhelpful they handle ctrl+C but fail to handle log off.I'm using windows7 & netbeans 6.9 .Is OS and IDE have some effect on shutdownhook ?,plz reply and help me for getting the solution of my problem.... – Ajeet Jul 30 '11 at 17:11
  • I was running that program outside of IDE through the command prompt. – helios Jul 30 '11 at 19:24