Programming Search⌘K

Patternadvanced

Coarse-grained lock

Also called Coarse-Grained Lock, shared version, shared lock, root lock, group lock.

A coarse-grained lock is one lock for a group of related objects, such as a customer and its addresses. A change to any member of the group takes the lock of the group.

Family
architectural
Intent
Lock a set of related objects with a single lock.

Intent

A coarse-grained lock "Locks a set of related objects with a single lock."1 The objects of a group share one version or one lock. A session that changes any member of the group must take that one lock.

Problem

"Objects can often be edited as a group. Perhaps you have a customer and its set of addresses. If so, when using the application it makes sense to lock all of these items if you want to lock any one of them."1

A lock for each object makes this hard. "Having a separate lock for individual objects presents a number of challenges. First, anyone manipulating them has to write code that can find them all in order to lock them."1 With an Optimistic offline lock, the session must load each member to check its version. "And with Pessimistic Offline Lock a large lock set is a management headache and increases lock table contention."1

A rule of the group can also break. For example, a customer can have at most one primary address. If each address has its own version, two sessions can each make a different address the primary one, and each save changes a different row. Each check passes, and the group breaks the rule.

Solution

"A Coarse-Grained Lock is a single lock that covers many objects. It not only simplifies the locking action itself but also frees you from having to load all the members of a group in order to lock them."1

There are two usual designs:2

  • The shared version. All the members of the group point to one version object, or to one version row in the database. For an optimistic lock, a save of any member checks and increases that one version. For a pessimistic lock, the lock is on the shared version.
  • The root lock. The group has a root, such as the customer for its addresses. A session that changes a member finds the root and locks the root. The members have no lock of their own.
  customer 1 ----------------+
  address 1 (customer 1) ----+---> version of the group "customer 1": 1
  address 2 (customer 1) ----+

  bob saves a change to customer 1: check version 1, set version 2
  ann saves a change to address 2:  check version 1, the version is 2: conflict

In the following program, the customer and an address share one version object. The save of the customer by Bob changes the version, so the save of the address by Ann fails.

class Version:
    def __init__(self):
        self.value = 1


shared = Version()  # one version object for the whole group
customer = {"name": "Acme Ltd", "version": shared}
address = {"street": "9 Oak Road", "version": shared}


def save(member, read_version):
    if member["version"].value != read_version:
        return "conflict"
    member["version"].value += 1  # a change to any member changes the version of all of them
    return "ok"


ann_read = bob_read = shared.value  # both sessions read version 1 of the group
print("bob saves the customer:", save(customer, bob_read))
print("ann saves an address:", save(address, ann_read))
print("version of the group:", shared.value)
Output
bob saves the customer: ok
ann saves an address: conflict
version of the group: 2

Example

Each example file has a customer with two addresses. The customer row holds the name of its lock, and one table holds the version of each lock. Each session loads the whole group with its version. Ann makes 1 Elm Street the primary address, and Bob makes 9 Oak Road the primary address. Each session changes both addresses, because the rule of the group allows at most one primary address. The save of Ann checks the version of the group and succeeds, and the version becomes 2. The save of Bob checks the version and finds a conflict. At the end, the database has one primary address, and each save needed only one check.

PythonGitHub
import copy


class ConflictError(Exception):
    pass


# The tables. A customer and its addresses form one group, with one shared version.
versions = {"customer 1": 1}
customers = {1: {"name": "Acme Ltd", "lock": "customer 1"}}
addresses = {
    1: {"customer": 1, "street": "1 Elm Street", "primary": False},
    2: {"customer": 1, "street": "9 Oak Road", "primary": False},
}


class Group:
    """A session's copy of the customer and its addresses, with the version of the group."""

    def __init__(self, customer_id):
        self.customer_id = customer_id
        self.lock = customers[customer_id]["lock"]
        self.version = versions[self.lock]
        self.customer = copy.deepcopy(customers[customer_id])
        self.addresses = {a: copy.deepcopy(r) for a, r in addresses.items() if r["customer"] == customer_id}

    def make_primary(self, address_id):
        # The rule of the group: at most one primary address for each customer.
        for a, r in self.addresses.items():
            r["primary"] = a == address_id

    def primary(self):
        return [r["street"] for r in self.addresses.values() if r["primary"]]


checks = 0


def save(group):
    global checks
    checks += 1  # one check for the whole group, however many members changed
    if versions[group.lock] != group.version:
        raise ConflictError(f"the group of customer {group.customer_id} changed (version {versions[group.lock]})")
    versions[group.lock] += 1
    group.version = versions[group.lock]
    customers[group.customer_id] = copy.deepcopy(group.customer)
    for a, r in group.addresses.items():
        addresses[a] = copy.deepcopy(r)


def try_save(who, group):
    try:
        save(group)
        print(f"{who} saves: ok, group version {group.version}")
    except ConflictError as e:
        print(f"{who} saves: conflict: {e}")


ann, bob = Group(1), Group(1)
print("customer 1:", ann.customer["name"], "with", len(ann.addresses), "addresses, group version", ann.version)
ann.make_primary(1)
print("ann makes 1 Elm Street the primary address")
bob.make_primary(2)
print("bob makes 9 Oak Road the primary address")
try_save("ann", ann)
try_save("bob", bob)
print("primary addresses in the database:", ", ".join(r["street"] for r in addresses.values() if r["primary"]))
print("version checks:", checks)
Output
customer 1: Acme Ltd with 2 addresses, group version 1
ann makes 1 Elm Street the primary address
bob makes 9 Oak Road the primary address
ann saves: ok, group version 2
bob saves: conflict: the group of customer 1 changed (version 2)
primary addresses in the database: 1 Elm Street
version checks: 2
  • Verdict: idiom. The customer row holds the name of its lock, customer 1, and the versions table holds one version for that name. Each address belongs to the customer, so a save of the group checks and increases that one version.
  • Group loads the customer and all its addresses together, and save writes them together after one check. The checks counter shows that the group needs one check for each save, however many members changed.
JavaGitHub
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class Main {
    static class ConflictException extends Exception {
        ConflictException(String message) {
            super(message);
        }
    }

    static class Customer {
        String name;
        final String lock;

        Customer(String name, String lock) {
            this.name = name;
            this.lock = lock;
        }

        Customer copy() {
            return new Customer(name, lock);
        }
    }

    static class Address {
        final int customer;
        final String street;
        boolean primary;

        Address(int customer, String street, boolean primary) {
            this.customer = customer;
            this.street = street;
            this.primary = primary;
        }

        Address copy() {
            return new Address(customer, street, primary);
        }
    }

    // The tables. A customer and its addresses form one group, with one shared version.
    static final Map<String, Integer> versions = new HashMap<>();
    static final Map<Integer, Customer> customers = new HashMap<>();
    static final Map<Integer, Address> addresses = new TreeMap<>();
    static int checks = 0;

    // A session's copy of the customer and its addresses, with the version of the group.
    static class Group {
        final int customerId;
        final String lock;
        int version;
        final Customer customer;
        final Map<Integer, Address> addresses = new TreeMap<>();

        Group(int customerId) {
            this.customerId = customerId;
            Customer c = customers.get(customerId);
            this.lock = c.lock;
            this.version = versions.get(lock);
            this.customer = c.copy();
            for (Map.Entry<Integer, Address> e : Main.addresses.entrySet()) {
                if (e.getValue().customer == customerId) {
                    this.addresses.put(e.getKey(), e.getValue().copy());
                }
            }
        }

        // The rule of the group: at most one primary address for each customer.
        void makePrimary(int addressId) {
            for (Map.Entry<Integer, Address> e : addresses.entrySet()) {
                e.getValue().primary = e.getKey() == addressId;
            }
        }
    }

    static void save(Group group) throws ConflictException {
        checks++; // one check for the whole group, however many members changed
        int current = versions.get(group.lock);
        if (current != group.version) {
            throw new ConflictException("the group of customer " + group.customerId + " changed (version " + current + ")");
        }
        versions.put(group.lock, current + 1);
        group.version = current + 1;
        customers.put(group.customerId, group.customer.copy());
        for (Map.Entry<Integer, Address> e : group.addresses.entrySet()) {
            addresses.put(e.getKey(), e.getValue().copy());
        }
    }

    static void trySave(String who, Group group) {
        try {
            save(group);
            System.out.println(who + " saves: ok, group version " + group.version);
        } catch (ConflictException e) {
            System.out.println(who + " saves: conflict: " + e.getMessage());
        }
    }

    public static void main(String[] args) {
        versions.put("customer 1", 1);
        customers.put(1, new Customer("Acme Ltd", "customer 1"));
        addresses.put(1, new Address(1, "1 Elm Street", false));
        addresses.put(2, new Address(1, "9 Oak Road", false));

        Group ann = new Group(1);
        Group bob = new Group(1);
        System.out.println("customer 1: " + ann.customer.name + " with " + ann.addresses.size() + " addresses, group version " + ann.version);
        ann.makePrimary(1);
        System.out.println("ann makes 1 Elm Street the primary address");
        bob.makePrimary(2);
        System.out.println("bob makes 9 Oak Road the primary address");
        trySave("ann", ann);
        trySave("bob", bob);
        List<String> primary = new ArrayList<>();
        for (Address a : addresses.values()) {
            if (a.primary) {
                primary.add(a.street);
            }
        }
        System.out.println("primary addresses in the database: " + String.join(", ", primary));
        System.out.println("version checks: " + checks);
    }
}
Output
customer 1: Acme Ltd with 2 addresses, group version 1
ann makes 1 Elm Street the primary address
bob makes 9 Oak Road the primary address
ann saves: ok, group version 2
bob saves: conflict: the group of customer 1 changed (version 2)
primary addresses in the database: 1 Elm Street
version checks: 2
  • Verdict: idiom. Group holds copies of the Customer and of each Address, and the lock name of the customer is the key into versions. save throws the checked ConflictException when the shared version changed.
  • The addresses are in a TreeMap, so the program lists them in the order of their ids. With Jakarta Persistence, a lock with OPTIMISTIC_FORCE_INCREMENT on the customer increases its version when only an address changes.
JavaScriptGitHub
class ConflictError extends Error {}

// The tables. A customer and its addresses form one group, with one shared version.
const versions = new Map([["customer 1", 1]]);
const customers = new Map([[1, { name: "Acme Ltd", lock: "customer 1" }]]);
const addresses = new Map([
  [1, { customer: 1, street: "1 Elm Street", primary: false }],
  [2, { customer: 1, street: "9 Oak Road", primary: false }],
]);

// A session's copy of the customer and its addresses, with the version of the group.
class Group {
  constructor(customerId) {
    this.customerId = customerId;
    this.lock = customers.get(customerId).lock;
    this.version = versions.get(this.lock);
    this.customer = { ...customers.get(customerId) };
    this.addresses = new Map();
    for (const [a, r] of addresses) if (r.customer === customerId) this.addresses.set(a, { ...r });
  }

  // The rule of the group: at most one primary address for each customer.
  makePrimary(addressId) {
    for (const [a, r] of this.addresses) r.primary = a === addressId;
  }
}

let checks = 0;

function save(group) {
  checks++; // one check for the whole group, however many members changed
  const current = versions.get(group.lock);
  if (current !== group.version) {
    throw new ConflictError(`the group of customer ${group.customerId} changed (version ${current})`);
  }
  versions.set(group.lock, current + 1);
  group.version = current + 1;
  customers.set(group.customerId, { ...group.customer });
  for (const [a, r] of group.addresses) addresses.set(a, { ...r });
}

function trySave(who, group) {
  try {
    save(group);
    console.log(`${who} saves: ok, group version ${group.version}`);
  } catch (e) {
    if (!(e instanceof ConflictError)) throw e;
    console.log(`${who} saves: conflict: ${e.message}`);
  }
}

const ann = new Group(1);
const bob = new Group(1);
console.log(`customer 1: ${ann.customer.name} with ${ann.addresses.size} addresses, group version ${ann.version}`);
ann.makePrimary(1);
console.log("ann makes 1 Elm Street the primary address");
bob.makePrimary(2);
console.log("bob makes 9 Oak Road the primary address");
trySave("ann", ann);
trySave("bob", bob);
const primary = [...addresses.values()].filter((r) => r.primary).map((r) => r.street);
console.log("primary addresses in the database:", primary.join(", "));
console.log("version checks:", checks);
Output
customer 1: Acme Ltd with 2 addresses, group version 1
ann makes 1 Elm Street the primary address
bob makes 9 Oak Road the primary address
ann saves: ok, group version 2
bob saves: conflict: the group of customer 1 changed (version 2)
primary addresses in the database: 1 Elm Street
version checks: 2
  • Verdict: idiom. The tables are Map objects, and the group copies each row with the spread syntax, so the copies of the two sessions do not share objects with the tables.
  • save reads the shared version, compares it with the version that the group read, and then writes the customer and the addresses. There is no await in save, so no other code can run between the check and the write.
package main

import (
	"errors"
	"fmt"
	"strings"
)

var errConflict = errors.New("conflict")

type customer struct {
	name string
	lock string
}

type address struct {
	id       int
	customer int
	street   string
	primary  bool
}

// The tables. A customer and its addresses form one group, with one shared version.
var (
	versions  = map[string]int{"customer 1": 1}
	customers = map[int]customer{1: {name: "Acme Ltd", lock: "customer 1"}}
	addresses = []address{
		{id: 1, customer: 1, street: "1 Elm Street"},
		{id: 2, customer: 1, street: "9 Oak Road"},
	}
	checks = 0
)

// group is a session's copy of the customer and its addresses, with the version of the group.
type group struct {
	customerID int
	lock       string
	version    int
	customer   customer
	addresses  []address
}

func load(customerID int) *group {
	c := customers[customerID]
	g := &group{customerID: customerID, lock: c.lock, version: versions[c.lock], customer: c}
	for _, a := range addresses {
		if a.customer == customerID {
			g.addresses = append(g.addresses, a)
		}
	}
	return g
}

// makePrimary keeps the rule of the group: at most one primary address for each customer.
func (g *group) makePrimary(addressID int) {
	for i := range g.addresses {
		g.addresses[i].primary = g.addresses[i].id == addressID
	}
}

func save(g *group) error {
	checks++ // one check for the whole group, however many members changed
	current := versions[g.lock]
	if current != g.version {
		return fmt.Errorf("%w: the group of customer %d changed (version %d)", errConflict, g.customerID, current)
	}
	versions[g.lock] = current + 1
	g.version = current + 1
	customers[g.customerID] = g.customer
	for _, a := range g.addresses {
		for i := range addresses {
			if addresses[i].id == a.id {
				addresses[i] = a
			}
		}
	}
	return nil
}

func trySave(who string, g *group) {
	if err := save(g); err != nil {
		fmt.Printf("%s saves: %v\n", who, err)
		return
	}
	fmt.Printf("%s saves: ok, group version %d\n", who, g.version)
}

func main() {
	ann, bob := load(1), load(1)
	fmt.Printf("customer 1: %s with %d addresses, group version %d\n", ann.customer.name, len(ann.addresses), ann.version)
	ann.makePrimary(1)
	fmt.Println("ann makes 1 Elm Street the primary address")
	bob.makePrimary(2)
	fmt.Println("bob makes 9 Oak Road the primary address")
	trySave("ann", ann)
	trySave("bob", bob)
	var primary []string
	for _, a := range addresses {
		if a.primary {
			primary = append(primary, a.street)
		}
	}
	fmt.Println("primary addresses in the database:", strings.Join(primary, ", "))
	fmt.Println("version checks:", checks)
}
Output
customer 1: Acme Ltd with 2 addresses, group version 1
ann makes 1 Elm Street the primary address
bob makes 9 Oak Road the primary address
ann saves: ok, group version 2
bob saves: conflict: the group of customer 1 changed (version 2)
primary addresses in the database: 1 Elm Street
version checks: 2
  • Verdict: idiom. load copies the customer struct and the address structs into the group, because Go copies a struct value on assignment. save returns an error that wraps errConflict, so a caller can test it with errors.Is.
  • The addresses are a slice and not a map, because the order of a range over a map is not defined.
RustGitHub
use std::collections::BTreeMap;

#[derive(Clone)]
struct Customer {
    name: String,
    lock: String,
}

#[derive(Clone)]
struct Address {
    id: u32,
    customer: u32,
    street: String,
    primary: bool,
}

// The tables. A customer and its addresses form one group, with one shared version.
struct Db {
    versions: BTreeMap<String, u32>,
    customers: BTreeMap<u32, Customer>,
    addresses: Vec<Address>,
    checks: u32,
}

// A session's copy of the customer and its addresses, with the version of the group.
struct Group {
    customer_id: u32,
    lock: String,
    version: u32,
    customer: Customer,
    addresses: Vec<Address>,
}

impl Group {
    fn load(db: &Db, customer_id: u32) -> Group {
        let customer = db.customers[&customer_id].clone();
        Group {
            customer_id,
            lock: customer.lock.clone(),
            version: db.versions[&customer.lock],
            addresses: db.addresses.iter().filter(|a| a.customer == customer_id).cloned().collect(),
            customer,
        }
    }

    // The rule of the group: at most one primary address for each customer.
    fn make_primary(&mut self, address_id: u32) {
        for a in &mut self.addresses {
            a.primary = a.id == address_id;
        }
    }
}

fn save(db: &mut Db, group: &mut Group) -> Result<(), String> {
    db.checks += 1; // one check for the whole group, however many members changed
    let current = db.versions[&group.lock];
    if current != group.version {
        return Err(format!("the group of customer {} changed (version {})", group.customer_id, current));
    }
    db.versions.insert(group.lock.clone(), current + 1);
    group.version = current + 1;
    db.customers.insert(group.customer_id, group.customer.clone());
    for a in &group.addresses {
        for row in db.addresses.iter_mut().filter(|r| r.id == a.id) {
            *row = a.clone();
        }
    }
    Ok(())
}

fn try_save(db: &mut Db, who: &str, group: &mut Group) {
    match save(db, group) {
        Ok(()) => println!("{} saves: ok, group version {}", who, group.version),
        Err(e) => println!("{} saves: conflict: {}", who, e),
    }
}

fn main() {
    let mut db = Db {
        versions: BTreeMap::from([("customer 1".to_string(), 1)]),
        customers: BTreeMap::from([(1, Customer { name: "Acme Ltd".to_string(), lock: "customer 1".to_string() })]),
        addresses: vec![
            Address { id: 1, customer: 1, street: "1 Elm Street".to_string(), primary: false },
            Address { id: 2, customer: 1, street: "9 Oak Road".to_string(), primary: false },
        ],
        checks: 0,
    };
    let mut ann = Group::load(&db, 1);
    let mut bob = Group::load(&db, 1);
    println!("customer 1: {} with {} addresses, group version {}", ann.customer.name, ann.addresses.len(), ann.version);
    ann.make_primary(1);
    println!("ann makes 1 Elm Street the primary address");
    bob.make_primary(2);
    println!("bob makes 9 Oak Road the primary address");
    try_save(&mut db, "ann", &mut ann);
    try_save(&mut db, "bob", &mut bob);
    let primary: Vec<&str> = db.addresses.iter().filter(|a| a.primary).map(|a| a.street.as_str()).collect();
    println!("primary addresses in the database: {}", primary.join(", "));
    println!("version checks: {}", db.checks);
}
Output
customer 1: Acme Ltd with 2 addresses, group version 1
ann makes 1 Elm Street the primary address
bob makes 9 Oak Road the primary address
ann saves: ok, group version 2
bob saves: conflict: the group of customer 1 changed (version 2)
primary addresses in the database: 1 Elm Street
version checks: 2
  • Verdict: idiom. Group::load clones the rows into the group, and save takes &mut Db, so the compiler allows no other access to the tables between the check and the write.
  • save returns Result<(), String>, and try_save prints the conflict with a match.

Consequences

Benefits.

  • One lock to take. The code locks the group with one call, and does not need to find all the members.
  • Fewer loads. An optimistic check reads one version, not the version of each member.
  • Rules of the group stay true. Two sessions cannot change two members of the same group at the same time, so a rule across the members, such as one primary address, holds.
  • A smaller lock table. A pessimistic lock manager keeps one lock for each group.

Liabilities.

Locks on single objects miss a conflict of the group. In the following program, each address has its own version. Each session changes one row, and each check passes, so the customer gets two primary addresses.

This code runs but gives a wrong answer on purpose.

# Wrong: each address has its own version, so nothing locks the group.
addresses = {1: {"primary": False, "version": 1}, 2: {"primary": False, "version": 1}}


def save(address_id, primary, read_version):
    row = addresses[address_id]
    if row["version"] != read_version:
        return "conflict"
    addresses[address_id] = {"primary": primary, "version": read_version + 1}
    return "ok"


# Both sessions read both addresses, and both are not primary.
# Each session sets one address as primary and saves only the row that it changed.
print("ann sets address 1:", save(1, True, 1))
print("bob sets address 2:", save(2, True, 1))
print("primary addresses:", [a for a, r in addresses.items() if r["primary"]])
Output
ann sets address 1: ok
bob sets address 2: ok
primary addresses: [1, 2]

Give the customer and its addresses one shared version, and make each save of a member check it.

More conflicts. Two users who change different members of the same group now conflict, even when their changes do not touch each other. A group that is too large makes the users wait or fail often.

Finding the root. With a root lock, the code must go from a member to its root before it can lock. In a Data Mapper, this can mean more loads, or a Lazy Load of the root.2

Every save must use the shared lock. A save of a member that skips the version of the group gives back the bug of the wrong program. An Implicit lock puts the check in shared code.

When not to use it

When the objects change on their own. If the members have no rule in common and users often edit different members, separate locks give more concurrency.

When the group is not clear. A coarse-grained lock needs a clear owner for each member, such as the customer of an address. Objects that many groups share do not fit one group.

Shared optimistic version. The members point to one version object, as in the example.2

Shared pessimistic lock. The lock manager locks the shared version, so one lock covers the group.2

Root optimistic lock. The session increases the version of the root when it changes a member. Jakarta Persistence has the lock mode OPTIMISTIC_FORCE_INCREMENT, where the entity manager "must also force an update (increment) to the entity’s version column."3 A lock with this mode on the root changes its version when only a member changed.

Related patterns. The group is often an aggregate, with the root as its entry point. A Dependent Mapping or a Foreign Key Mapping holds the link from each member to its root. The lock itself is an Optimistic offline lock or a Pessimistic offline lock. A Unit of Work can check the version of the group once in each commit.

Known uses

  • Jakarta Persistence, where OPTIMISTIC_FORCE_INCREMENT and PESSIMISTIC_FORCE_INCREMENT on the root entity force a change of its version.3

References

  1. David Rice and Matt Foemmel, Catalog of Patterns of Enterprise Application Architecture, Coarse-Grained Lock, pattern summary
  2. Martin Fowler, Patterns of Enterprise Application Architecture, Addison-Wesley, 2002, Chapter 16, Offline Concurrency Patterns, Coarse-Grained Lock
  3. Jakarta Persistence 3.2 specification, 3.5.4.1. OPTIMISTIC, OPTIMISTIC_FORCE_INCREMENT; 3.5.4.2. PESSIMISTIC_READ, PESSIMISTIC_WRITE, PESSIMISTIC_FORCE_INCREMENT

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)
WritingW4 complete
  • a review of the text: no review record reviews/85CQYF/text.yaml