Time limit on the execution of a Java function

java, multithreading

Solution

You will always get a `IllegalMonitorStateException` if you are calling `wait()` on an object that you are not `synchronized` on.

try {
    // you need this to do the wait
    synchronized (thread) {
       thread.wait(10000);
    }
} catch (InterruptedException e) {
    System.err.println("interrupted.");
}

If you are waiting for the `thread` to finish then you probably are trying to do a:

try {
    thread.join(10000);
} catch (InterruptedException e) {
    Thread.currentThread().interrupt();
    System.err.println("interrupted.");
}

Unfortunately, you do not know at that point if the thread is running because `join` doesn't return whether or not it timed out (grumble). So you need to test if the `thread.isAlive()` after the join.

If you are asking how you can cancel the `thread` if it runs for longer than `10000` millis, then the right thing to do is use `thread.interrupt()`. This will cause any `sleep()` or `wait()` methods to throw an `InterruptedException` and it will set the interrupt flag on the thread.

To use the interrupt flag your thread should be doing something like:

   while (!Thread.currentThread.isInterrupted()) {
       // do it's thread stuff
   }

Also, it is always a good pattern to do something like the following because once the `InterruptedException` is thrown, the interrupt flag has been cleared:

} catch (InterruptedException e) {
    // set the interrupt flag again because InterruptedException clears it
    Thread.currentThread.interrupt();
    System.err.println("interrupted.");
}

Problem

I am trying to construct two threads, thread A is the main thread and thread B is the second thread, thread B is updating a variable through a time consuming function (this variable should be shared between both threads, because eventually thread A needs to use that variable as well), but I want thread A to terminate thread B if thread B takes too long to complete (using an exception). What I tried is the following: ``` Thread thread = new Thread() { public void run() { /// run something that could take a long time } }; synchronized (thread) { thread.start(); } System.err.println("Waiting for thread and terminating it if it did not stop."); try { thread.wait(10000); } catch (InterruptedException e) { System.err.println("interrupted."); } ``` Should that give the expected behavior of terminating a behavior in case it has run more than 10 seconds? The thread object gets deleted after the wait, because the method that runs the thread returns. Right now, what happens with this code is that I always get java.lang.IllegalMonitorStateException on the wait(10000) command.

Original source