Skip to content

Instantly share code, notes, and snippets.

@nsivabalan
Created September 11, 2020 17:41
Show Gist options
  • Save nsivabalan/a8d4e3e4a5d6ec3649b323922de2e9a6 to your computer and use it in GitHub Desktop.
Save nsivabalan/a8d4e3e4a5d6ec3649b323922de2e9a6 to your computer and use it in GitHub Desktop.
public class CustomStopWatch implements Runnable {
private final long timeoutMs;
private final TimeoutCallBack callBack;
private AtomicBoolean eventTriggered = new AtomicBoolean(false);
public CustomStopWatch(TimeoutCallBack callBack, long timeoutMs) {
this.callBack = callBack;
this.timeoutMs = timeoutMs;
}
@Override
public void run() {
try {
waitUntilTimeout();
} catch (InterruptedException e) {
throw new IllegalStateException("IE thrown ", e);
}
}
private synchronized void waitUntilTimeout() throws InterruptedException {
while(true) {
eventTriggered.set(false);
this.wait(timeoutMs);
if(!eventTriggered.get()){
callBack.onTimeout();
// what to do
break;
} else {
// go back to wait again
}
}
}
public synchronized void triggerEvent(){
eventTriggered.set(true);
this.notifyAll();
}
interface TimeoutCallBack {
void onTimeout();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment