2

console java application. Someone kill java.exe process by Task Manager. How can I write to logs some information at this moment before application is terminated?

Thread.currentThread().setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
    public void uncaughtException(Thread t, Throwable e) { ..... }
}); 

OR

Runtime.getRuntime().addShutdownHook(new Thread() {
    public void run() { ..... }
});

don't execute in such situation

5 Answers 5

6

This is not possible. Shutdown hooks will only be executed in an orderly shutdown:

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.

You can send another signal that will trigger an orderly shutdown like SIGINT. Killing a application should be the last resort after the application did not respond.

0
3

some practical solutions have already been suggested, but another is to ping-pong a "last status" message between 2 applications that monitor each other. When one dies, the other one writes the last received message to a log file. Users can't kill both processes quickly enough with Task Manager.

1
  • but can kill both at almost the same time programatically. I.e., there isn't a fool proof way, but in practise, almost always works.
    – Chii
    Dec 14, 2009 at 13:18
2

Some sort of solution is to write something to a log file all the time. This way you'll see whatever was the "last breath" of the Java program.

2
  • @Dominic: depends of how you set up the log file rotation. Dec 14, 2009 at 12:57
  • A bit cumbersome, but it seems like the most reliable solution among the suggestions.
    – Buhb
    Dec 14, 2009 at 13:02
2

you might try to start java.exe via a small naive (e.g. c++) application using a CreateProcess (in windows ) this application will then continue running monitoring the java process handle. if the java process is gone it can log it.

1

Give your users an orderly way to shut down the system, and tell them to stop using Task Manager to do so.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.