Programming Search⌘K

Patternadvanced

Balking

Also called balking, balking pattern, balk.

A balking method runs its action only when the object is in the right state. In any other state it returns at once, or throws, and does not wait for the state to change.

Family
concurrency
Intent
Make a method refuse a request at once when the object is not in a state that allows it, so that the caller does not block and the action runs at most when it makes sense.
Also called
Balk

Intent

The balking pattern only executes an action on an object when the object is in a particular state.1 If an object reads ZIP files and a caller invokes a get method when the ZIP file is not open, the object "balks" at the request.1

Problem

Several threads call the same method, but the action only makes sense in some states. A save of a document should not start while another save is in progress, and it is not needed when nothing has changed. A caller that waits for the right state, as in guarded suspension, can wait for an unknown time, and the work it would do is often not needed any more.

Solution

Under a lock, test the state. If the state is wrong, return at once. If it is right, change the state to show that the action is in progress, release the lock, and run the action. When the action ends, take the lock again and set the state back.

 save() ──► lock ──► saving or not changed? ──yes──► unlock ──► return False (balk)
                       │ no
                       ▼
                saving = True, changed = False ──► unlock
                       ▼
                write the file (no lock held)
                       ▼
                lock ──► saving = False ──► unlock ──► return True

In the Java example on Wikipedia, the synchronized block makes sure that if there are multiple calls to the job method, only one proceeds, and the other calls return with nothing.1 The method that clears the flag is also synchronized, because the only way to guarantee that another thread sees a change to a field is to synchronize all access to it. A volatile Boolean would also work for that one field.1

Example

A document is edited, and a first save starts and stays in progress. While it runs, 7 other threads call save, and all of them balk. After the first save ends, a save with no changes balks too, and a save after a new edit runs.

calls during a save: 7
calls that balked: 7
saves run: 1
save with no changes: balked
save after an edit: ran
saves run: 2

The examples for each language show the same program.

PythonGitHub
import threading


class Document:
    def __init__(self, write):
        self._lock = threading.Lock()
        self._write = write  # the slow part of a save
        self._changed = False
        self._saving = False
        self.saves = 0

    def edit(self):
        with self._lock:
            self._changed = True

    def save(self):
        """Save the document. Return False at once if a save cannot start now."""
        with self._lock:
            if self._saving or not self._changed:
                return False  # balk: the object is not in the right state
            self._saving = True
            self._changed = False
        self._write()
        with self._lock:
            self._saving = False
            self.saves += 1
        return True


started = threading.Event()
release = threading.Event()


def slow_write():
    started.set()
    release.wait()  # the first save stays in progress until the other calls end


doc = Document(slow_write)
doc.edit()
first = threading.Thread(target=doc.save)
first.start()
started.wait()

results = []
callers = [threading.Thread(target=lambda: results.append(doc.save())) for _ in range(7)]
for t in callers:
    t.start()
for t in callers:
    t.join()
release.set()
first.join()

print("calls during a save:", len(results))
print("calls that balked:", results.count(False))
print("saves run:", doc.saves)
print("save with no changes:", "ran" if doc.save() else "balked")
doc.edit()
print("save after an edit:", "ran" if doc.save() else "balked")
print("saves run:", doc.saves)
Output
calls during a save: 7
calls that balked: 7
saves run: 1
save with no changes: balked
save after an edit: ran
saves run: 2
  • Verdict: idiom. A threading.Lock makes the test and the change of the _saving flag one step, and the write runs without the lock.
#include <atomic>
#include <functional>
#include <future>
#include <iostream>
#include <mutex>
#include <thread>
#include <vector>

class Document {
public:
    explicit Document(std::function<void()> write) : write_(std::move(write)) {}

    void edit() {
        std::lock_guard<std::mutex> lock(m_);
        changed_ = true;
    }

    // Saves the document. Returns false at once if a save cannot start now.
    bool save() {
        {
            std::lock_guard<std::mutex> lock(m_);
            if (saving_ || !changed_) return false;  // balk: the object is not in the right state
            saving_ = true;
            changed_ = false;
        }
        write_();
        std::lock_guard<std::mutex> lock(m_);
        saving_ = false;
        saves_++;
        return true;
    }

    int saves() {
        std::lock_guard<std::mutex> lock(m_);
        return saves_;
    }

private:
    std::mutex m_;
    std::function<void()> write_;  // the slow part of a save
    bool changed_ = false, saving_ = false;
    int saves_ = 0;
};

int main() {
    std::promise<void> started_p, release_p;
    std::shared_future<void> release = release_p.get_future().share();
    std::atomic<bool> first_write{true};
    Document doc([&] {
        if (first_write.exchange(false)) started_p.set_value();
        release.wait();  // the first save stays in progress until the other calls end
    });
    doc.edit();
    std::thread first([&] { doc.save(); });
    started_p.get_future().wait();

    std::atomic<int> calls{0}, balked{0};
    std::vector<std::thread> callers;
    for (int i = 0; i < 7; i++) {
        callers.emplace_back([&] {
            calls++;
            if (!doc.save()) balked++;
        });
    }
    for (auto& t : callers) t.join();
    release_p.set_value();
    first.join();

    std::cout << "calls during a save: " << calls << "\n";
    std::cout << "calls that balked: " << balked << "\n";
    std::cout << "saves run: " << doc.saves() << "\n";
    std::cout << "save with no changes: " << (doc.save() ? "ran" : "balked") << "\n";
    doc.edit();
    std::cout << "save after an edit: " << (doc.save() ? "ran" : "balked") << "\n";
    std::cout << "saves run: " << doc.saves() << "\n";
}
Output
calls during a save: 7
calls that balked: 7
saves run: 1
save with no changes: balked
save after an edit: ran
saves run: 2
  • Verdict: stdlib. A std::lock_guard on a std::mutex makes the test and the change of the saving_ flag one step.
JavaGitHub
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

public class Main {
    static class Document {
        private final Runnable write; // the slow part of a save
        private boolean changed = false;
        private boolean saving = false;
        int saves = 0;

        Document(Runnable write) {
            this.write = write;
        }

        synchronized void edit() {
            changed = true;
        }

        // Saves the document. Returns false at once if a save cannot start now.
        boolean save() {
            synchronized (this) {
                if (saving || !changed) return false; // balk: the object is not in the right state
                saving = true;
                changed = false;
            }
            write.run();
            synchronized (this) {
                saving = false;
                saves++;
            }
            return true;
        }

        synchronized int saves() {
            return saves;
        }
    }

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch started = new CountDownLatch(1);
        CountDownLatch release = new CountDownLatch(1);
        Document doc = new Document(() -> {
            started.countDown();
            try {
                release.await(); // the first save stays in progress until the other calls end
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });
        doc.edit();
        Thread first = new Thread(doc::save);
        first.start();
        started.await();

        AtomicInteger calls = new AtomicInteger();
        AtomicInteger balked = new AtomicInteger();
        List<Thread> callers = new ArrayList<>();
        for (int i = 0; i < 7; i++) {
            callers.add(new Thread(() -> {
                calls.incrementAndGet();
                if (!doc.save()) balked.incrementAndGet();
            }));
        }
        for (Thread t : callers) t.start();
        for (Thread t : callers) t.join();
        release.countDown();
        first.join();

        System.out.println("calls during a save: " + calls.get());
        System.out.println("calls that balked: " + balked.get());
        System.out.println("saves run: " + doc.saves());
        System.out.println("save with no changes: " + (doc.save() ? "ran" : "balked"));
        doc.edit();
        System.out.println("save after an edit: " + (doc.save() ? "ran" : "balked"));
        System.out.println("saves run: " + doc.saves());
    }
}
Output
calls during a save: 7
calls that balked: 7
saves run: 1
save with no changes: balked
save after an edit: ran
saves run: 2
  • Verdict: native. A synchronized block makes the test and the change of the saving flag one step.
using System;
using System.Collections.Generic;
using System.Threading;

class Document
{
    private readonly object gate = new object();
    private readonly Action write; // the slow part of a save
    private bool changed = false;
    private bool saving = false;
    private int saves = 0;

    public Document(Action write) => this.write = write;

    public void Edit()
    {
        lock (gate) changed = true;
    }

    // Saves the document. Returns false at once if a save cannot start now.
    public bool Save()
    {
        lock (gate)
        {
            if (saving || !changed) return false; // balk: the object is not in the right state
            saving = true;
            changed = false;
        }
        write();
        lock (gate)
        {
            saving = false;
            saves++;
        }
        return true;
    }

    public int Saves()
    {
        lock (gate) return saves;
    }
}

class Program
{
    static void Main()
    {
        var started = new ManualResetEventSlim(false);
        var release = new ManualResetEventSlim(false);
        var doc = new Document(() =>
        {
            started.Set();
            release.Wait(); // the first save stays in progress until the other calls end
        });
        doc.Edit();
        var first = new Thread(() => doc.Save());
        first.Start();
        started.Wait();

        int calls = 0, balked = 0;
        var callers = new List<Thread>();
        for (int i = 0; i < 7; i++)
        {
            callers.Add(new Thread(() =>
            {
                Interlocked.Increment(ref calls);
                if (!doc.Save()) Interlocked.Increment(ref balked);
            }));
        }
        foreach (var t in callers) t.Start();
        foreach (var t in callers) t.Join();
        release.Set();
        first.Join();

        Console.WriteLine("calls during a save: " + calls);
        Console.WriteLine("calls that balked: " + balked);
        Console.WriteLine("saves run: " + doc.Saves());
        Console.WriteLine("save with no changes: " + (doc.Save() ? "ran" : "balked"));
        doc.Edit();
        Console.WriteLine("save after an edit: " + (doc.Save() ? "ran" : "balked"));
        Console.WriteLine("saves run: " + doc.Saves());
    }
}
Output
calls during a save: 7
calls that balked: 7
saves run: 1
save with no changes: balked
save after an edit: ran
saves run: 2
  • Verdict: native. A lock statement makes the test and the change of the saving flag one step.
JavaScriptGitHub
// The tasks share one thread. The await in save lets other calls run.
class Document {
  constructor(write) {
    this.write = write; // the slow part of a save
    this.changed = false;
    this.saving = false;
    this.saves = 0;
  }

  edit() {
    this.changed = true;
  }

  // Saves the document. Returns false at once if a save cannot start now.
  async save() {
    if (this.saving || !this.changed) return false; // balk: the object is not in the right state
    this.saving = true;
    this.changed = false;
    await this.write();
    this.saving = false;
    this.saves++;
    return true;
  }
}

async function main() {
  let release;
  const released = new Promise((resolve) => (release = resolve));
  const doc = new Document(() => released); // the first save stays in progress
  doc.edit();
  const first = doc.save();

  const results = await Promise.all(Array.from({ length: 7 }, () => doc.save()));
  release();
  await first;

  const word = (ran) => (ran ? "ran" : "balked");
  console.log("calls during a save:", results.length);
  console.log("calls that balked:", results.filter((r) => !r).length);
  console.log("saves run:", doc.saves);
  console.log("save with no changes:", word(await doc.save()));
  doc.edit();
  console.log("save after an edit:", word(await doc.save()));
  console.log("saves run:", doc.saves);
}

main();
Output
calls during a save: 7
calls that balked: 7
saves run: 1
save with no changes: balked
save after an edit: ran
saves run: 2
  • Verdict: idiom. The tasks share one thread, so the test and the change of saving run with no await between them.
TypeScriptGitHub
// The tasks share one thread. The await in save lets other calls run.
class Document {
  write: () => Promise<void>;
  changed: boolean;
  saving: boolean;
  saves: number;

  constructor(write: () => Promise<void>) {
    this.write = write; // the slow part of a save
    this.changed = false;
    this.saving = false;
    this.saves = 0;
  }

  edit(): void {
    this.changed = true;
  }

  // Saves the document. Returns false at once if a save cannot start now.
  async save(): Promise<boolean> {
    if (this.saving || !this.changed) return false; // balk: the object is not in the right state
    this.saving = true;
    this.changed = false;
    await this.write();
    this.saving = false;
    this.saves++;
    return true;
  }
}

async function main(): Promise<void> {
  let release: () => void = () => {};
  const released = new Promise<void>((resolve) => (release = resolve));
  const doc = new Document(() => released); // the first save stays in progress
  doc.edit();
  const first = doc.save();

  const results = await Promise.all(Array.from({ length: 7 }, () => doc.save()));
  release();
  await first;

  const word = (ran: boolean): string => (ran ? "ran" : "balked");
  console.log("calls during a save:", results.length);
  console.log("calls that balked:", results.filter((r) => !r).length);
  console.log("saves run:", doc.saves);
  console.log("save with no changes:", word(await doc.save()));
  doc.edit();
  console.log("save after an edit:", word(await doc.save()));
  console.log("saves run:", doc.saves);
}

main();
Output
calls during a save: 7
calls that balked: 7
saves run: 1
save with no changes: balked
save after an edit: ran
saves run: 2
  • Verdict: idiom. The tasks share one thread, so the test and the change of saving run with no await between them.
package main

import (
	"fmt"
	"sync"
	"sync/atomic"
)

type Document struct {
	mu      sync.Mutex
	write   func() // the slow part of a save
	changed bool
	saving  bool
	saves   int
}

func (d *Document) Edit() {
	d.mu.Lock()
	defer d.mu.Unlock()
	d.changed = true
}

// Save saves the document. It returns false at once if a save cannot start now.
func (d *Document) Save() bool {
	d.mu.Lock()
	if d.saving || !d.changed {
		d.mu.Unlock()
		return false // balk: the object is not in the right state
	}
	d.saving = true
	d.changed = false
	d.mu.Unlock()
	d.write()
	d.mu.Lock()
	defer d.mu.Unlock()
	d.saving = false
	d.saves++
	return true
}

func (d *Document) Saves() int {
	d.mu.Lock()
	defer d.mu.Unlock()
	return d.saves
}

func word(ran bool) string {
	if ran {
		return "ran"
	}
	return "balked"
}

func main() {
	started := make(chan struct{})
	release := make(chan struct{})
	var once sync.Once
	doc := &Document{write: func() {
		once.Do(func() { close(started) })
		<-release // the first save stays in progress until the other calls end
	}}
	doc.Edit()
	done := make(chan struct{})
	go func() {
		doc.Save()
		close(done)
	}()
	<-started

	var calls, balked atomic.Int64
	var wg sync.WaitGroup
	for i := 0; i < 7; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			calls.Add(1)
			if !doc.Save() {
				balked.Add(1)
			}
		}()
	}
	wg.Wait()
	close(release)
	<-done

	fmt.Println("calls during a save:", calls.Load())
	fmt.Println("calls that balked:", balked.Load())
	fmt.Println("saves run:", doc.Saves())
	fmt.Println("save with no changes:", word(doc.Save()))
	doc.Edit()
	fmt.Println("save after an edit:", word(doc.Save()))
	fmt.Println("saves run:", doc.Saves())
}
Output
calls during a save: 7
calls that balked: 7
saves run: 1
save with no changes: balked
save after an edit: ran
saves run: 2
  • Verdict: stdlib. A sync.Mutex makes the test and the change of the saving flag one step.
RustGitHub
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Barrier, Mutex};
use std::thread;

#[derive(Default)]
struct State {
    changed: bool,
    saving: bool,
    saves: usize,
}

struct Document {
    state: Mutex<State>,
    write: Box<dyn Fn() + Send + Sync>, // the slow part of a save
}

impl Document {
    fn edit(&self) {
        self.state.lock().unwrap().changed = true;
    }

    /// Saves the document. Returns false at once if a save cannot start now.
    fn save(&self) -> bool {
        {
            let mut s = self.state.lock().unwrap();
            if s.saving || !s.changed {
                return false; // balk: the object is not in the right state
            }
            s.saving = true;
            s.changed = false;
        }
        (self.write)();
        let mut s = self.state.lock().unwrap();
        s.saving = false;
        s.saves += 1;
        true
    }

    fn saves(&self) -> usize {
        self.state.lock().unwrap().saves
    }
}

fn main() {
    // The first save waits at the start barrier and then at the release barrier.
    let start = Arc::new(Barrier::new(2));
    let release = Arc::new(Barrier::new(2));
    let writes = Arc::new(AtomicUsize::new(0));
    let doc = {
        let (start, release, writes) = (Arc::clone(&start), Arc::clone(&release), Arc::clone(&writes));
        Arc::new(Document {
            state: Mutex::new(State::default()),
            write: Box::new(move || {
                if writes.fetch_add(1, Ordering::SeqCst) == 0 {
                    start.wait();
                    release.wait(); // stay in progress until the other calls end
                }
            }),
        })
    };
    doc.edit();
    let first = {
        let doc = Arc::clone(&doc);
        thread::spawn(move || doc.save())
    };
    start.wait();

    let callers: Vec<_> = (0..7)
        .map(|_| {
            let doc = Arc::clone(&doc);
            thread::spawn(move || doc.save())
        })
        .collect();
    let results: Vec<bool> = callers.into_iter().map(|t| t.join().unwrap()).collect();
    release.wait();
    first.join().unwrap();

    let word = |ran: bool| if ran { "ran" } else { "balked" };
    println!("calls during a save: {}", results.len());
    println!("calls that balked: {}", results.iter().filter(|r| !**r).count());
    println!("saves run: {}", doc.saves());
    println!("save with no changes: {}", word(doc.save()));
    doc.edit();
    println!("save after an edit: {}", word(doc.save()));
    println!("saves run: {}", doc.saves());
}
Output
calls during a save: 7
calls that balked: 7
saves run: 1
save with no changes: balked
save after an edit: ran
saves run: 2
  • Verdict: stdlib. A Mutex<State> makes the test and the change of the saving flag one step.

Consequences

Benefits:

  • The caller never blocks for the state to change, so a duplicate request costs only one test under a lock.
  • The action runs at most once at a time, and only when it is useful.
  • The method tells the caller what happened. It can return a value, or throw an exception: an IllegalStateException in Java, or an InvalidOperationException in C#.1

Liabilities:

  • The method does not always do what its name says, so each caller must check the result.
  • The caller must handle the refusal. A balked request is lost unless the caller tries again later.
  • The test and the change of state must be one atomic step. If they are not, two threads can both pass the test.

This program tests the flag and sets it in two separate steps without a lock. A barrier makes the second thread run its test between the test and the change of the first thread:

This code runs but gives a wrong answer on purpose.

import threading

saving = False
running = 0
most_running = 0
both_checked = threading.Barrier(2)
counter_lock = threading.Lock()


def save():
    global saving, running, most_running
    # Wrong: the check and the change of state are not one atomic step.
    if saving:
        return False
    both_checked.wait()  # here a second thread runs the same check
    saving = True
    with counter_lock:
        running += 1
        most_running = max(most_running, running)
    both_checked.wait()  # stay in the save until both are inside
    with counter_lock:
        running -= 1
    saving = False
    return True


threads = [threading.Thread(target=save) for _ in range(2)]
for t in threads:
    t.start()
for t in threads:
    t.join()
print("saves running at once:", most_running)
Output
saves running at once: 2

When not to use it

Do not balk when the caller needs the action to happen. Then it must wait, or queue the request. Guarded suspension is used when the wait for the right state is finite and reasonable. If the wait would be indefinite or unacceptably long, the balking pattern may be preferred.2

  • Throw instead of return. Java's IllegalStateException signals that a method has been invoked at an illegal or inappropriate time.3 .NET's InvalidOperationException is thrown when a method call is invalid for the object's current state.4 Python's Thread.start() raises a RuntimeError if it is called more than once on the same thread object.5
  • Try-lock. A lock that balks: Python's Lock.acquire(blocking=False) does not block. If a call with blocking set to True would block, it returns False immediately.5
import threading

lock = threading.Lock()
print("first acquire:", lock.acquire(blocking=False))
print("second acquire while held:", lock.acquire(blocking=False))
lock.release()
print("acquire after release:", lock.acquire(blocking=False))
lock.release()
Output
first acquire: True
second acquire while held: False
acquire after release: True
  • Go's TryLock tries to lock a mutex and reports whether it succeeded. The Go documentation notes that correct uses of TryLock are rare, and its use is often a sign of a deeper problem.6

Guarded suspension is the alternative: it waits for the state instead of refusing the call.1

Known uses

  • Java code that throws IllegalStateException when the application is not in an appropriate state for the requested operation.3
  • .NET methods that throw InvalidOperationException for the current state of an object.4
  • Python Thread.start() and Lock.acquire(blocking=False).5
  • Go Mutex.TryLock.6

References

  1. Balking pattern, Wikipedia, lead; Usage; Implementation
  2. Guarded suspension, Wikipedia, Usage
  3. Java SE 21 API, java.lang.IllegalStateException, class description
  4. InvalidOperationException Class, .NET API reference, class description
  5. threading, Thread-based parallelism, Python documentation, Lock.acquire; Thread.start
  6. Go standard library, package sync, func (*Mutex) TryLock

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source