4

I have the following problem: I run an iterative algorithm written in Java on a workstation. The workstation uses SGE under the hood. For each job you have to set a soft and hard time limit. When the soft time limit is reached, the running program receives a SIGUSR1. When the hard time limit is reached, it is a SIGKILL instead.

I would like to be able to handle the SIGUSR1 by stopping at the current iteration and writing the current solution to a file. The canonical way to do this in a C application would be to trap the signal in a signal handler, set a boolean flag which is checked periodically during the iteration and triggers the termination.

The java program looks like this:

public class TestInterrupt
{
    public static volatile boolean shouldTerminate = false;

    public static void main(final String[] args) throws InterruptedException
    {
        int i = 0;
        while (++i < 100)
        {
            Thread.sleep(1000);

            if(shouldTerminate) {
                break;
            }
        }

        // write data to file here.
    }
}

There are no signal handlers in java (afaik). I wrapped the java application in a bash script which can trap the signal. Question is, how can I notify the java application? Is there some standard mechanism for this?

I have seen this similar thread which revolves around using shutdown handlers. The answer was accepted. However, as far as I saw (and as far as the API docs tell), shutdown hooks are run as threads only after shutdown has been initiated rather then immediately when a SIGINT or similar is received, so I don't see how they would be useful to trap a signal.

Community
  • 1
  • 1
hfhc2
  • 4,182
  • 2
  • 27
  • 56

0 Answers0