1

I have this sample application from here

public class ExampleSignalHandler {
public static void main(String... args) throws InterruptedException {
    final long start = System.nanoTime();
    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        public void run() {
            System.out.format("\nProgram execution took %f seconds\n", (System.nanoTime() - start) / 1e9f);
        }
    }));
    int counter = 0;
    while(true) {
        System.out.println(counter++);
        Thread.sleep(500);
    }
}
}

This works just fine, but if I do this in my present application it is not executed on

kill -TERM <pid>

but on

kill -1 <pid>
kill -KILL <pid>

But with those signals I do not have enough time to do my operations before closing the application.

there are a few Threads and a JNI Wrapper used in my application, what can cause the issue that the shutdownHook is not called on kill -TERM?

I need this because my applications uses a network protocol, where I can subscribe to variables. This handles MUST be unsubscribed before closing, otherwise the server run out of memory because of too much handles after a while(Server is not in my control!)

Community
  • 1
  • 1
user2071938
  • 2,055
  • 6
  • 28
  • 60
  • 1
    `kill -TERM` or `kill - 9` is force shutdown and free local resources, shutdownhooks dont work with this. – Amey Jadiye Sep 28 '15 at 07:48
  • with the test application above it works! – user2071938 Sep 28 '15 at 07:53
  • can u suggest an alternative? I want to exit my application from OS(Linux) and do some things before shutting the application down – user2071938 Sep 28 '15 at 08:01
  • You can't intercept `kill -KILL` (aka `kill -9`) - that tells the OS to terminate the program immediately - no shutdown hooks *can* be run in that case. – Anya Shenanigans Sep 28 '15 at 08:14
  • as I mention in my question I want to send kill -TERM, which is working it the test application above, but not in mine(which is a multithreaded application which uses a jni wrapper as well). My question is, why is the shutdownHook not executed in my application when I send kill -TERM – user2071938 Sep 28 '15 at 08:23
  • It sounds like your native code may be installing a signal handler which overrides the java shutdown hook. You cannot rely on shutdown hook behaviour for this - you just have no guarantees that hook will get called – Anya Shenanigans Sep 28 '15 at 08:30
  • problem is with your code, shutdownhook only work on main thread, you are trying to hook it with thread, obviously it wont work, check the "exception handling in java" ... better exception handling can solve your problem – Amey Jadiye Sep 28 '15 at 08:48
  • the hook is added in the in the main thread – user2071938 Sep 28 '15 at 10:11

0 Answers0