1

Is it possible make some handler that will do something when user shutdown computer with Java on Windows XP (optional, win7)? How?

Thanks.

2 Answers 2

4

It is possible to add a shutdown hook to your Java program which is invoked if the JVM is shutdown for any reason (other than System.exit()) including O/S shutdown. Is that what you want?

Use: java.lang.Runtime.addShutdownHook(Thread):

Runtime.getRuntime().addShutdownHook(new Thread() {
    public void run() {
        // shutdown code here
        }
    });
Sign up to request clarification or add additional context in comments.

1 Comment

iirc, at leats in Java 6, shutdown hooks still run even if System.exit() is called - the only time they are not is if the process is sent a kill command (or the OS equivalent)
4

a shutdown hook should do the job.

From API Doc:

Registers a new virtual-machine shutdown hook. 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.
Runtime.getRuntime().addShutdownHook(new Thread() {
  public void run() {
    // do something
  }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.