How to implement a efficient timeout in java

stormsam picture stormsam · Jul 24, 2012 · Viewed 12.9k times · Source

There are n object which perform some actions. After performing an action a timestamp will be updated. Now I want to implement a timeout-thread which verifies if a timestamp is older than for example 60 seconds.

My first solution was to do that with a thread (while-loop + sleep) which is holding a list with all objects including the last timestamp. Now I have the problem that there is a worst-case scenario where the thread needs 59 seconds plus sleep time to decide for a timeout.

I’m searching for a solution like a Timer where it is possible to update the delay time.

Any ideas?

Answer

Adrian Shum picture Adrian Shum · Jul 25, 2012

I think using a monitor object with wait/notify is reasonable (you may use Condition with await/signal if you are using JDK >= 5)

idea is simple:

Worker thread:

doYourActualWork();
synchronized(jobFinishedMonitor) {
    updateTimestamp();

    jobFinishedMonitor.notify();
}

Timeout thread:

synchronized(jobFinishedMonitor) {
    while(within60Second(timestamp)) {
        jobFinishedMonitor.wait(60);
    }
    if (within60Second(timestamp)) {
        timeoutHappened=true;
    }
 }
 if (timeoutHappened) {
     // do timeout handling
 }