2

I have an abstract Java class which runs as a Thread. It does not have a main method. Only run(), start(), stop(), etc.

I want to add a SignalHandler to the class. I've tried this:

Add this to the initialize method:

  addSignalHandler();

That executes this method:

  public void addSignalHandler() {
     Signal.handle(new Signal("INT"), new SignalHandler() {
         public void handle(Signal sig) {
             System.out.println("I shall exit now");
             keepRunning = false;
             System.out.println("I shall exit now - keepRunning is false");
         }
     });
     System.out.println("Added signal handler");
}

And I see the 'Added signal handler' in my log file.

Now I want to kill the process from my Linux server, so I run this:

  kill -SIGINT PID

Nothing happens. The process still runs and I don't see 'I shall exit now'.

EDIT:

My run() method contains this:

  while (keepRunning) {
      // do stuff
  }
lulu88
  • 1,694
  • 5
  • 27
  • 41
  • Maybe this answer can help you: http://stackoverflow.com/a/11387729/1050015 – Carlo Feb 13 '14 at 08:33
  • Do you see the traces ("I shall exit now", etc.) when you try to kill your process? What is keepRunning? Is your program frequently checking it in its main loop? Please show us its usage – Jorge_B Feb 13 '14 at 08:39
  • Edited the question with my run() method containing the loop. – lulu88 Feb 13 '14 at 08:40
  • keepRunning must have volatile modifier or you have to do something equivalent. Otherwise the traces may be printed and the thread don't notice the change in the variable because the value may be cached. – aalku Feb 13 '14 at 08:43
  • I have this: private volatile boolean keepRunning = true; – lulu88 Feb 13 '14 at 08:45
  • Shouldn't be that `SIGINT` instead of `INT` in the Java code? – rlegendi Feb 13 '14 at 11:08

0 Answers0