Java Concurrency Interview

Patterns and antipatterns question 151 of 180 mid

What is the balking pattern, and where would you use it?

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.

patterns

Quiz yourself on Patterns and antipatterns Suggest a correction