How could I “pause” a method in between an execution, and trigger it externally to continue the execution of this method?
The Thread is a servlet, and the executeAndWait method is started by a button click.
Now I want to do polling on a SessionScoped variable.
If this variable changes its state (eg to true), the polling/waiting method should continue.
I first though about Observer pattern. But with this I can just trigger the execution of methods. But I need to sleep/wait and trigger the continue of a method.
How else could this be done apart from polling to a “global” variable.?
class MyThread {
@Inject
MyBean bean;
doExecuteAndWait() {
//this waits for the var to turn into "true" state
while(!bean.isVarValid()) {
Thread.sleep(1000);
}
//continue execution if somevar is set to true externally
}
}
class MySignal {
@Inject
MyBean bean;
//this triggers the continuation of the method from class above
toggleVar() {
bean.setVarValid(true);
}
}
@SessionScoped
class MyBean() {
varValid = false;
isVarValid() {
return varValid;
}
setVarValid(Boolean status) {
this.varValid = status;
}
}
You could use a CountDownLatch.
Initialize it to
1, callawait()inMyThread, and then call thecountDown()method fromMySignalwhen it should be released.This way you don’t need to keep polling the value of a variable.