Guarded suspension
In concurrent programming, guarded suspension[1] is a software design pattern for managing operations that require both a lock to be acquired and a precondition to be satisfied before the operation can be executed. The guarded suspension pattern is typically applied to method calls in object-oriented programs, and involves suspending the method call, and the calling thread, until the precondition (acting as a guard) is satisfied. UsageBecause it is blocking, the guarded suspension pattern is generally only used when the developer knows that a method call will be suspended for a finite and reasonable period of time. If a method call is suspended for too long, then the overall program will slow down or stop, waiting for the precondition to be satisfied. If the developer knows that the method call suspension will be indefinite or for an unacceptably long period, then the balking pattern may be preferred. ImplementationIn Java, the Object class provides the public class Example {
synchronized void guardedMethod() {
while (!preCondition()) {
try {
// Continue to wait
wait();
// …
} catch (InterruptedException e) {
// …
}
}
// Actual task implementation
}
synchronized void alterObjectStateMethod() {
// Change the object state
// …
// Inform waiting threads
notify();
}
}
An example of an actual implementation would be a queue object with a See also
Notes
References
|