i wanna create a java application that must perform some esse开发者_运维知识库ntial 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....
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:
- Placed a fake pause to keep JVM alive long enough for you to trigger Windows logoff
- 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());
}
}
}
}
精彩评论