Programming Search⌘K

Patternadvanced

Strategized Locking

Also called pluggable locking, parameterized locking, lock strategy.

Strategized Locking makes the lock of a component a parameter, so one implementation serves single-threaded and multi-threaded use with the lock that fits each case.

Family
concurrency
Intent
Make the synchronization of a reusable component a pluggable type, so the component can be tuned for each concurrency use-case without a separate copy of its code.

Intent

The Strategized Locking pattern strategizes a component's synchronization to increase its flexibility and reusability without degrading its performance or maintainability.1

Problem

The paper's example is the file cache of a Web server. One version, File Cache ST, implements a single-threaded file cache that requires no locking. Another version, File Cache Thread Mutex, uses a mutex to serialize multiple threads that access the cache concurrently.1 Maintaining multiple separate implementations of similar file cache components can be tedious since future enhancements and fixes must be updated consistently in each component implementation.1

A family of components whose synchronization strategies are hard-coded into their implementations fails to resolve two forces:1

  • Ease of performance tuning. If the synchronization strategy is hard-coded, it is time-consuming to modify the component to support new, more efficient synchronization strategies. For example, a completely new class must be written to use a readers-writer lock instead of a thread mutex.1
  • Ease of maintenance and enhancement. If there are multiple copies of the same basic components, version-skew is likely to occur, since changes to one component may not be applied consistently to the others.1

Solution

Strategize a component's synchronization aspects by making them "pluggable" types. Define instances of these pluggable types as data members that the component's method implementations use to perform the synchronization strategies that an application or a service configures into the component.1

FileCache(lock):            # the lock is a parameter
  find(path):
    guard(lock)             # Scoped Locking inside the method
    look up or insert path

FileCache(NullMutex)        # single-threaded: no cost
FileCache(ThreadMutex)      # multi-threaded: serialized
FileCache(RWLock)           # many readers

The paper gives two forms:1

  • Parameterized types. Add a LOCK template parameter to the component. The template can be instantiated with any LOCK type that conforms to the acquire and release signature, and it need not inherit from an abstract base class.1
  • Polymorphism. Pass a polymorphic Lock object to the component's initialization method. A common way to implement it is to use the Bridge pattern.1

The parameterized type approach should be used when the locking strategy is known at compile-time, and the polymorphic approach when it is not known until run-time.1 A surprisingly useful strategy is the Null Mutex, which defines an efficient locking strategy for single-threaded applications and components.1 All of its methods are empty inlined functions that can be completely removed by optimizing compilers, and it is an example of the Null Object pattern.1

Example

The example files show one file cache class in each language, used with two strategies. A null lock serves one thread that looks up three paths. A real lock serves four threads that each do 1,000 lookups. The FileCache code does not change between the two cases. The program prints:

Null_Mutex cache: 2 files, 3 lookups
Thread_Mutex cache: 3 files, 4000 lookups
PythonGitHub
import threading


class NullMutex:
    """A lock for one thread: both methods do nothing."""

    def acquire(self):
        pass

    def release(self):
        pass


class FileCache:
    def __init__(self, lock):
        self._lock = lock  # the locking strategy is a parameter
        self.files = {}
        self.lookups = 0

    def find(self, path):
        self._lock.acquire()
        try:
            self.lookups += 1
            if path not in self.files:
                self.files[path] = "mapped " + path
            return self.files[path]
        finally:
            self._lock.release()


single = FileCache(NullMutex())
for path in ["/a.html", "/b.html", "/a.html"]:
    single.find(path)
print(f"Null_Mutex cache: {len(single.files)} files, {single.lookups} lookups")

multi = FileCache(threading.Lock())


def worker():
    for i in range(1000):
        multi.find(["/a.html", "/b.html", "/c.html"][i % 3])


threads = [threading.Thread(target=worker) for _ in range(4)]
for t in threads:
    t.start()
for t in threads:
    t.join()
print(f"Thread_Mutex cache: {len(multi.files)} files, {multi.lookups} lookups")
Output
Null_Mutex cache: 2 files, 3 lookups
Thread_Mutex cache: 3 files, 4000 lookups
  • Verdict: idiom. Any object with acquire and release methods can be the strategy, so threading.Lock and the null class fit without a common base class.
#include <iostream>
#include <map>
#include <mutex>
#include <string>
#include <thread>
#include <vector>

// A lock for one thread: both functions do nothing.
struct NullMutex {
    void lock() {}
    void unlock() {}
};

template <class LOCK>  // the locking strategy is a parameter
class FileCache {
public:
    std::string find(const std::string& path) {
        std::lock_guard<LOCK> guard(lock_);
        ++lookups;
        auto it = files.find(path);
        if (it == files.end()) it = files.emplace(path, "mapped " + path).first;
        return it->second;
    }
    std::map<std::string, std::string> files;
    int lookups = 0;

private:
    LOCK lock_;
};

int main() {
    FileCache<NullMutex> single;
    for (const char* path : {"/a.html", "/b.html", "/a.html"}) single.find(path);
    std::cout << "Null_Mutex cache: " << single.files.size() << " files, "
              << single.lookups << " lookups\n";

    FileCache<std::mutex> multi;
    const char* paths[] = {"/a.html", "/b.html", "/c.html"};
    std::vector<std::thread> threads;
    for (int w = 0; w < 4; ++w)
        threads.emplace_back([&] {
            for (int i = 0; i < 1000; ++i) multi.find(paths[i % 3]);
        });
    for (auto& t : threads) t.join();
    std::cout << "Thread_Mutex cache: " << multi.files.size() << " files, "
              << multi.lookups << " lookups\n";
}
Output
Null_Mutex cache: 2 files, 3 lookups
Thread_Mutex cache: 3 files, 4000 lookups
  • Verdict: idiom. This is the parameterized type form. std::lock_guard<LOCK> accepts NullMutex because it has lock and unlock.
JavaGitHub
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Main {
    interface Lockable {
        void acquire();
        void release();
    }

    // A lock for one thread: both methods do nothing.
    static class NullMutex implements Lockable {
        public void acquire() {}
        public void release() {}
    }

    static class ThreadMutex implements Lockable {
        private final Lock lock = new ReentrantLock();
        public void acquire() { lock.lock(); }
        public void release() { lock.unlock(); }
    }

    static class FileCache {
        private final Lockable lock; // the locking strategy is a parameter
        final Map<String, String> files = new HashMap<>();
        int lookups = 0;

        FileCache(Lockable lock) { this.lock = lock; }

        String find(String path) {
            lock.acquire();
            try {
                lookups++;
                return files.computeIfAbsent(path, p -> "mapped " + p);
            } finally {
                lock.release();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        FileCache single = new FileCache(new NullMutex());
        for (String path : new String[] {"/a.html", "/b.html", "/a.html"}) single.find(path);
        System.out.println("Null_Mutex cache: " + single.files.size() + " files, " + single.lookups + " lookups");

        FileCache multi = new FileCache(new ThreadMutex());
        String[] paths = {"/a.html", "/b.html", "/c.html"};
        List<Thread> threads = new ArrayList<>();
        for (int w = 0; w < 4; w++) {
            Thread t = new Thread(() -> {
                for (int i = 0; i < 1000; i++) multi.find(paths[i % 3]);
            });
            threads.add(t);
            t.start();
        }
        for (Thread t : threads) t.join();
        System.out.println("Thread_Mutex cache: " + multi.files.size() + " files, " + multi.lookups + " lookups");
    }
}
Output
Null_Mutex cache: 2 files, 3 lookups
Thread_Mutex cache: 3 files, 4000 lookups
  • Verdict: idiom. This is the polymorphic form. FileCache sees only the Lockable interface, and each strategy is a class that implements it.
using System;
using System.Collections.Generic;
using System.Threading;

interface ILockable
{
    void Acquire();
    void Release();
}

// A lock for one thread: both methods do nothing.
class NullMutex : ILockable
{
    public void Acquire() { }
    public void Release() { }
}

class ThreadMutex : ILockable
{
    private readonly object gate = new object();
    public void Acquire() => Monitor.Enter(gate);
    public void Release() => Monitor.Exit(gate);
}

class FileCache
{
    private readonly ILockable lockable; // the locking strategy is a parameter
    public readonly Dictionary<string, string> Files = new();
    public int Lookups;

    public FileCache(ILockable lockable) => this.lockable = lockable;

    public string Find(string path)
    {
        lockable.Acquire();
        try
        {
            Lookups++;
            if (!Files.TryGetValue(path, out var file))
            {
                file = "mapped " + path;
                Files[path] = file;
            }
            return file;
        }
        finally
        {
            lockable.Release();
        }
    }
}

static class Program
{
    static void Main()
    {
        var single = new FileCache(new NullMutex());
        foreach (var path in new[] { "/a.html", "/b.html", "/a.html" }) single.Find(path);
        Console.WriteLine($"Null_Mutex cache: {single.Files.Count} files, {single.Lookups} lookups");

        var multi = new FileCache(new ThreadMutex());
        var paths = new[] { "/a.html", "/b.html", "/c.html" };
        var threads = new List<Thread>();
        for (int w = 0; w < 4; w++)
        {
            var t = new Thread(() =>
            {
                for (int i = 0; i < 1000; i++) multi.Find(paths[i % 3]);
            });
            threads.Add(t);
            t.Start();
        }
        foreach (var t in threads) t.Join();
        Console.WriteLine($"Thread_Mutex cache: {multi.Files.Count} files, {multi.Lookups} lookups");
    }
}
Output
Null_Mutex cache: 2 files, 3 lookups
Thread_Mutex cache: 3 files, 4000 lookups
  • Verdict: idiom. This is the polymorphic form. FileCache sees only ILockable, and ThreadMutex adapts Monitor to that interface.
JavaScriptGitHub
// A lock for one task: it runs the body at once.
class NullMutex {
  run(body) {
    return body();
  }
}

// A lock for many tasks: each body waits for the one before it.
class TaskMutex {
  tail = Promise.resolve();
  async run(body) {
    const previous = this.tail;
    let release;
    this.tail = new Promise((resolve) => (release = resolve));
    await previous;
    try {
      return await body();
    } finally {
      release();
    }
  }
}

class FileCache {
  files = new Map();
  lookups = 0;
  constructor(lock) {
    this.lock = lock; // the locking strategy is a parameter
  }

  find(path) {
    return this.lock.run(async () => {
      this.lookups++;
      if (!this.files.has(path)) {
        await null; // another task can run here
        this.files.set(path, "mapped " + path);
      }
      return this.files.get(path);
    });
  }
}

async function main() {
  const single = new FileCache(new NullMutex());
  for (const path of ["/a.html", "/b.html", "/a.html"]) await single.find(path);
  console.log(`Null_Mutex cache: ${single.files.size} files, ${single.lookups} lookups`);

  const multi = new FileCache(new TaskMutex());
  const paths = ["/a.html", "/b.html", "/c.html"];
  const worker = async () => {
    for (let i = 0; i < 1000; i++) await multi.find(paths[i % 3]);
  };
  await Promise.all([worker(), worker(), worker(), worker()]);
  console.log(`Thread_Mutex cache: ${multi.files.size} files, ${multi.lookups} lookups`);
}

main();
Output
Null_Mutex cache: 2 files, 3 lookups
Thread_Mutex cache: 3 files, 4000 lookups
  • Verdict: idiom. JavaScript runs the tasks on one thread, so the second strategy orders async tasks, not threads. Any object with a run method can be the strategy.
TypeScriptGitHub
interface Lockable {
  run<T>(body: () => Promise<T>): Promise<T>;
}

// A lock for one task: it runs the body at once.
class NullMutex implements Lockable {
  run<T>(body: () => Promise<T>): Promise<T> {
    return body();
  }
}

// A lock for many tasks: each body waits for the one before it.
class TaskMutex implements Lockable {
  private tail: Promise<void> = Promise.resolve();
  async run<T>(body: () => Promise<T>): Promise<T> {
    const previous = this.tail;
    let release!: () => void;
    this.tail = new Promise<void>((resolve) => (release = resolve));
    await previous;
    try {
      return await body();
    } finally {
      release();
    }
  }
}

class FileCache {
  files = new Map<string, string>();
  lookups = 0;
  private lock: Lockable;
  constructor(lock: Lockable) {
    this.lock = lock; // the locking strategy is a parameter
  }

  find(path: string): Promise<string> {
    return this.lock.run(async () => {
      this.lookups++;
      if (!this.files.has(path)) {
        await null; // another task can run here
        this.files.set(path, "mapped " + path);
      }
      return this.files.get(path)!;
    });
  }
}

async function main(): Promise<void> {
  const single = new FileCache(new NullMutex());
  for (const path of ["/a.html", "/b.html", "/a.html"]) await single.find(path);
  console.log(`Null_Mutex cache: ${single.files.size} files, ${single.lookups} lookups`);

  const multi = new FileCache(new TaskMutex());
  const paths = ["/a.html", "/b.html", "/c.html"];
  const worker = async () => {
    for (let i = 0; i < 1000; i++) await multi.find(paths[i % 3]);
  };
  await Promise.all([worker(), worker(), worker(), worker()]);
  console.log(`Thread_Mutex cache: ${multi.files.size} files, ${multi.lookups} lookups`);
}

main();
Output
Null_Mutex cache: 2 files, 3 lookups
Thread_Mutex cache: 3 files, 4000 lookups
  • Verdict: idiom. JavaScript runs the tasks on one thread, so the second strategy orders async tasks, not threads. The Lockable interface is the strategy type.
package main

import (
	"fmt"
	"sync"
)

// NullMutex is a lock for one goroutine: both methods do nothing.
type NullMutex struct{}

func (NullMutex) Lock()   {}
func (NullMutex) Unlock() {}

type FileCache struct {
	lock    sync.Locker // the locking strategy is a parameter
	files   map[string]string
	lookups int
}

func NewFileCache(lock sync.Locker) *FileCache {
	return &FileCache{lock: lock, files: map[string]string{}}
}

func (c *FileCache) Find(path string) string {
	c.lock.Lock()
	defer c.lock.Unlock()
	c.lookups++
	if _, ok := c.files[path]; !ok {
		c.files[path] = "mapped " + path
	}
	return c.files[path]
}

func main() {
	single := NewFileCache(NullMutex{})
	for _, path := range []string{"/a.html", "/b.html", "/a.html"} {
		single.Find(path)
	}
	fmt.Printf("Null_Mutex cache: %d files, %d lookups\n", len(single.files), single.lookups)

	multi := NewFileCache(&sync.Mutex{})
	paths := []string{"/a.html", "/b.html", "/c.html"}
	var wg sync.WaitGroup
	for w := 0; w < 4; w++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			for i := 0; i < 1000; i++ {
				multi.Find(paths[i%3])
			}
		}()
	}
	wg.Wait()
	fmt.Printf("Thread_Mutex cache: %d files, %d lookups\n", len(multi.files), multi.lookups)
}
Output
Null_Mutex cache: 2 files, 3 lookups
Thread_Mutex cache: 3 files, 4000 lookups
  • Verdict: stdlib. sync.Locker is the interface with Lock and Unlock, and *sync.Mutex implements it.
RustGitHub
use std::cell::RefCell;
use std::collections::HashMap;
use std::sync::Mutex;
use std::thread;

type Files = HashMap<String, String>;

// The locking strategy: run a closure with access to the guarded data.
trait Strategy<T> {
    fn with<R>(&self, f: impl FnOnce(&mut T) -> R) -> R;
}

// A lock for one thread: no locking, only a run-time borrow check.
struct NullMutex<T>(RefCell<T>);

impl<T> Strategy<T> for NullMutex<T> {
    fn with<R>(&self, f: impl FnOnce(&mut T) -> R) -> R {
        f(&mut self.0.borrow_mut())
    }
}

impl<T> Strategy<T> for Mutex<T> {
    fn with<R>(&self, f: impl FnOnce(&mut T) -> R) -> R {
        f(&mut self.lock().unwrap())
    }
}

struct FileCache<L: Strategy<(Files, usize)>> {
    lock: L, // the locking strategy is a parameter
}

impl<L: Strategy<(Files, usize)>> FileCache<L> {
    fn find(&self, path: &str) -> String {
        self.lock.with(|(files, lookups)| {
            *lookups += 1;
            files
                .entry(path.to_string())
                .or_insert_with(|| format!("mapped {path}"))
                .clone()
        })
    }

    fn counts(&self) -> (usize, usize) {
        self.lock.with(|(files, lookups)| (files.len(), *lookups))
    }
}

fn main() {
    let single = FileCache { lock: NullMutex(RefCell::new((Files::new(), 0))) };
    for path in ["/a.html", "/b.html", "/a.html"] {
        single.find(path);
    }
    let (files, lookups) = single.counts();
    println!("Null_Mutex cache: {files} files, {lookups} lookups");

    let multi = FileCache { lock: Mutex::new((Files::new(), 0)) };
    let paths = ["/a.html", "/b.html", "/c.html"];
    thread::scope(|s| {
        for _ in 0..4 {
            s.spawn(|| {
                for i in 0..1000 {
                    multi.find(paths[i % 3]);
                }
            });
        }
    });
    let (files, lookups) = multi.counts();
    println!("Thread_Mutex cache: {files} files, {lookups} lookups");
}
Output
Null_Mutex cache: 2 files, 3 lookups
Thread_Mutex cache: 3 files, 4000 lookups
  • Verdict: idiom. This is the parameterized type form with a trait. RefCell is not Sync, so the compiler does not let threads share the NullMutex cache.

Consequences

Benefits:1

  • Enhanced flexibility and performance tuning. Because the synchronization aspects are strategized, it is straightforward to configure and tune a component for particular concurrency use-cases.1
  • Decreased maintenance effort. There is only one implementation, rather than a separate implementation for each concurrency use-case, which avoids version-skew.1

Liabilities:1

  • Obtrusive locking. If templates are used to parameterize locking aspects, this exposes the locking strategies to application code. One way to avoid this problem is to apply the polymorphic approach.1
  • Strategy-dependent self-deadlock. A component whose find method calls its bind method works well only with a lock with recursive mutex semantics or a Null Mutex. With a non-recursive mutex, the code will self-deadlock, because bind reacquires the lock already held by find.1

The second liability is easy to miss, because the same code works with one strategy and hangs with another. In this version, bind tries the lock with a timeout, so the program shows the failure instead of waiting forever. A reentrant lock may be acquired multiple times by the same thread, and a plain lock may not.2

This code runs but gives a wrong answer on purpose.

import threading


class FileCache:
    def __init__(self, lock):
        self.lock = lock
        self.files = {}

    def bind(self, path):
        if not self.lock.acquire(timeout=0.1):
            return False  # a real bind waits here forever
        self.files[path] = "mapped " + path
        self.lock.release()
        return True

    def find(self, path):
        with self.lock:
            if path not in self.files:
                return self.bind(path)  # takes the lock a second time
            return True


print("RLock strategy, find binds the file:", FileCache(threading.RLock()).find("/a.html"))
print("Lock strategy, find binds the file:", FileCache(threading.Lock()).find("/a.html"))
Output
RLock strategy, find binds the file: True
Lock strategy, find binds the file: False

The Thread-Safe Interface pattern removes this liability, because its implementation methods never take the lock.1

When not to use it

  • The component has one concurrency use-case, and it is not a reusable component. A hard-coded lock is then simpler, and there is no family of versions to keep in step.
  • Application code must not see the lock type, and the language has only the template form. The obtrusive locking liability applies then.1
  • The component calls its own locking methods, and it does not follow Thread-Safe Interface. Some strategies then self-deadlock.1
  • Scoped Locking. The Scoped Locking idiom uses Strategized Locking to parameterize various synchronization strategies into its guard class.1
  • Thread-Safe Interface. Components designed according to Strategized Locking should employ Thread-safe Interface, because it ensures that the component functions robustly and efficiently regardless of the type of locking strategy that is selected.1
  • Wrapper Facade. If the synchronization components that exist have incompatible interfaces, use the Wrapper Facade pattern to adapt them to the signatures that the component expects.1
  • Synchronization patterns. POSA2 puts Strategized Locking with Scoped Locking, Thread-Safe Interface and Double-Checked Locking Optimization.3
  • Standard library forms. The type parameter of std::lock_guard must meet the BasicLockable requirements, so a null mutex type can be the parameter.4 In Go, a Locker represents an object that can be locked and unlocked, and a component can hold that interface.5

A strategy can also measure. This version plugs a counting wrapper around a real lock to see how often the component locks. The FileCache class does not change.

import threading


class CountingLock:
    def __init__(self, inner):
        self.inner = inner
        self.acquires = 0

    def acquire(self):
        self.inner.acquire()
        self.acquires += 1

    def release(self):
        self.inner.release()


class FileCache:
    def __init__(self, lock):
        self.lock = lock
        self.files = {}

    def find(self, path):
        self.lock.acquire()
        try:
            return self.files.setdefault(path, "mapped " + path)
        finally:
            self.lock.release()


lock = CountingLock(threading.Lock())
cache = FileCache(lock)
for path in ["/a.html", "/b.html", "/a.html"]:
    cache.find(path)
print("files:", len(cache.files))
print("lock acquired:", lock.acquires, "times")
Output
files: 2
lock acquired: 3 times

Known uses

  • Booch Components. They were one of the first C++ class libraries to parameterize locking strategies with templates.1
  • ACE. The pattern is used extensively throughout the ACE object-oriented network programming toolkit.1
  • Aspect-Oriented Programming. The paper names AOP as a general methodology for systematically strategizing aspects that vary in applications and components.1
  • C++ and Go standard libraries. std::lock_guard takes the lock type as a template parameter, and Go code can depend on sync.Locker instead of a concrete mutex.45

References

  1. Douglas C. Schmidt, Strategized Locking, Thread-safe Interface, and Scoped Locking: Patterns and Idioms for Simplifying Multi-threaded C++ Components (C++ Report), 2 The Strategized Locking Pattern, sections 2.1 to 2.10
  2. threading, Thread-based parallelism, Python documentation, Lock objects; RLock objects
  3. Pattern-Oriented Software Architecture, Patterns for Concurrent and Networked Objects (POSA2), overview page, Table of Contents, 4 Synchronization Patterns
  4. std::lock_guard, cppreference.com, Template parameters
  5. sync package, Go standard library, type Locker

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/EWN7HA/text.yaml