Created
September 11, 2020 17:41
-
-
Save nsivabalan/a8d4e3e4a5d6ec3649b323922de2e9a6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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