Patterns and antipatterns question 151 of 180 mid
What is the balking pattern, and where would you use it?
- Retrying until the state is right
- Correct: If the object is not in the right state when a method is called, return immediately instead of waiting
- Blocking until another thread balks
- A rejection policy for thread pools
Balking is the "if you are already doing it, do nothing" pattern: check the state under the lock, and if the action is not appropriate right now, return at once rather than blocking.
void save() {
synchronized (this) {
if (!changed) {
return; // balk: nothing to do
}
changed = false;
}
writeToDisk(); // the slow part, outside the lock
}
Autosave, lazy refresh and idempotent start/stop methods are typical. Its opposite is guarded suspension, which waits for the state instead of giving up. Choosing between them is choosing whether a caller would rather be delayed or told no.
Quiz yourself on Patterns and antipatterns Suggest a correction