I'm trying to write a thread that monitors how long a blocking action takes. For example, I have a blocking action like this:
class BlockingThread extends Thread{
public volatile boolean success = false;
public volatile long startedTime = 0;
public void run(){
startedTime = System.currentTimeMillis();
success = doBlockingAction(); //no idea how long this action will take
}
}
and I want to have another Thread that will basically call a "timeout" function if the blocking action takes too long:
class MonitorThread extends Thread{
public void run(){
while(System.currentTimeMillis() - blockingThread.startedTime > TIMEOUT_DURATION)
{
..keep waiting until the time runs out..
}
if(!blockingThread.success){
listener.timeout();
//Took too long.
}
}
}
I'm having trouble understanding how to ensure that the BlockingThread is actually currently on the blocking action while I'm measuring time in the MonitorThread.
If I do something like this,
Thread blockingThread = new BlockingThread();
blockingThread.start();
Thread monitorThread = new MonitorThread();
monitorThread.start();
there is no guarantee that one of the threads actually starts running the code before the other, and therefore I currently have no way of knowing if my timeout thread is actually measuring the time of the blocking action correctly. I assume the answer has to do with locking and wait
ing but I can't figure it out.