I am trying to schedule a thread that wait for some condition to happen. If condition is true, return some result else again schedule itself to execute after some delay. To achieve this, I am using Executors
to schedule Callable<Boolean>
but it hangs after second rescheduling.
final ExecutorService executor = Executors.newFixedThreadPool(2);
final MutableBoolean status = new MutableBoolean(false);
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Waiting now to set status");
try {
Thread.sleep(5*1000);
System.out.println("status is now true");
status.setValue(true);
} catch (InterruptedException e) {
}
}
}).start();
Future<Boolean> future = executor.submit(new Callable<Boolean>() {
public int count=0;
@Override
public Boolean call() throws Exception {
if(status.isTrue()){
System.out.println("Condition has become true now");
return status.booleanValue();
} else {
System.out.println("Not true yet, count" + count++ + " Rescheduling");
Future<Boolean> future = executor.submit(this);
return future.get();
}
}
});
boolean finalStatus = future.get();
System.out.println("Final status" + finalStatus);
Output:
Waiting now to set status
Not true yet, count0 Rescheduling
Not true yet, count1 Rescheduling
status is now true
Any suggestions on what might be going wrong?
Thanks