Programming Search⌘K

Patternadvanced

Thread-Safe Interface

Also called thread-safe interface, interface and implementation methods, locked public methods.

Thread-Safe Interface lets only the public methods of a component take its lock, and they call private methods that never lock, so calls inside the component cannot self-deadlock.

Family
concurrency
Intent
Make calls between the methods of a thread-safe component avoid self-deadlock and take the lock no more often than needed.

Intent

The Thread-safe Interface pattern ensures that intracomponent method calls avoid self-deadlock and minimize locking overhead.1

Problem

Multi-threaded components typically contain multiple interface and implementation methods that perform computations on state that is encapsulated by the component.1 A lock protects that state, and component methods often call each other to carry out their computations.1 In components with poorly designed intra-component method invocation behavior, two forces are unresolved:1

  • Avoid self-deadlock. Self-deadlock will occur if one component method acquires a non-recursive component lock and calls another method that tries to reacquire the same lock.1
  • Minimal locking overhead. If a recursive component lock is selected to avoid the self-deadlock problem, additional overhead will be incurred to acquire and release the lock multiple times across intracomponent method calls.1

The paper's example is a file cache whose find method calls its bind method when a file is not in the cache.1

Solution

Structure components with intra-component method invocations according to two design conventions:1

  • Interface methods check. All interface methods, such as C++ public methods, should only acquire and release locks, thereby performing the synchronization checks at the "border" of the component. After the lock is acquired, the interface method should forward to an implementation method, which performs the actual method functionality.1
  • Implementation methods trust. Implementation methods, such as C++ private and protected methods, should trust that they are called with locks held and never acquire or release locks. Implementation methods should never call interface methods, since these methods acquire locks.1
find(path):            # interface method
  guard(lock)
  return find_i(path)

find_i(path):          # implementation method, lock held
  if check_cache_i(path) is none:
    bind_i(path)       # never bind(): it would lock again
  return check_cache_i(path)

As long as these design conventions are followed, components will avoid self-deadlock and minimize locking overhead.1 To implement the pattern, first determine the interface methods, and for each interface method define a corresponding implementation method.1

Example

The example files show the paper's file cache in each language with a lock that is not reentrant. The public bind and find methods take the lock. The find_i, check_cache_i and bind_i methods do the work. The program binds one file, then four workers each call find 1,000 times on three paths, and a last find reads one entry. Each of the 4,002 interface calls takes the lock once, and no call takes it twice. The program prints:

find /a.html: mapped /a.html
files cached: 4
lock acquisitions: 4002
PythonGitHub
import threading


class FileCache:
    def __init__(self):
        self._lock = threading.Lock()  # not reentrant
        self.files = {}
        self.acquires = 0

    # Interface methods: take the lock, then call an implementation method.
    def find(self, path):
        with self._lock:
            self.acquires += 1
            return self._find_i(path)

    def bind(self, path):
        with self._lock:
            self.acquires += 1
            self._bind_i(path)

    # Implementation methods: trust that the lock is held, never take it.
    def _find_i(self, path):
        file = self._check_cache_i(path)
        if file is None:
            self._bind_i(path)  # not bind(): that would take the lock again
            file = self._check_cache_i(path)
        return file

    def _check_cache_i(self, path):
        return self.files.get(path)

    def _bind_i(self, path):
        self.files[path] = "mapped " + path


cache = FileCache()
cache.bind("/index.html")
paths = ["/a.html", "/b.html", "/c.html"]


def worker():
    for i in range(1000):
        cache.find(paths[i % 3])


threads = [threading.Thread(target=worker) for _ in range(4)]
for t in threads:
    t.start()
for t in threads:
    t.join()
print("find /a.html:", cache.find("/a.html"))
print("files cached:", len(cache.files))
print("lock acquisitions:", cache.acquires)
Output
find /a.html: mapped /a.html
files cached: 4
lock acquisitions: 4002
  • Verdict: idiom. The leading underscore marks the implementation methods by convention only. threading.Lock is not reentrant, so a call from _find_i to find would block.
#include <iostream>
#include <map>
#include <mutex>
#include <optional>
#include <string>
#include <thread>
#include <vector>

class FileCache {
public:
    // Interface methods: take the lock, then call an implementation method.
    std::string find(const std::string& path) {
        std::lock_guard<std::mutex> guard(lock_);
        ++acquires;
        return find_i(path);
    }

    void bind(const std::string& path) {
        std::lock_guard<std::mutex> guard(lock_);
        ++acquires;
        bind_i(path);
    }

    std::map<std::string, std::string> files;
    int acquires = 0;

private:
    // Implementation methods: trust that the lock is held, never take it.
    std::string find_i(const std::string& path) {
        auto file = check_cache_i(path);
        if (!file) {
            bind_i(path);  // not bind(): that would take the lock again
            file = check_cache_i(path);
        }
        return *file;
    }

    std::optional<std::string> check_cache_i(const std::string& path) {
        auto it = files.find(path);
        if (it == files.end()) return std::nullopt;
        return it->second;
    }

    void bind_i(const std::string& path) { files[path] = "mapped " + path; }

    std::mutex lock_;  // not recursive
};

int main() {
    FileCache cache;
    cache.bind("/index.html");
    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) cache.find(paths[i % 3]);
        });
    for (auto& t : threads) t.join();
    std::cout << "find /a.html: " << cache.find("/a.html") << "\n";
    std::cout << "files cached: " << cache.files.size() << "\n";
    std::cout << "lock acquisitions: " << cache.acquires << "\n";
}
Output
find /a.html: mapped /a.html
files cached: 4
lock acquisitions: 4002
  • Verdict: idiom. Public members are the interface methods and private members are the implementation methods, which is the split the paper uses for C++.
JavaGitHub
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

public class Main {
    static class FileCache {
        private final ReentrantLock lock = new ReentrantLock();
        final Map<String, String> files = new HashMap<>();
        int acquires = 0;

        // Interface methods: take the lock, then call an implementation method.
        public String find(String path) {
            lock.lock();
            try {
                acquires++;
                return findI(path);
            } finally {
                lock.unlock();
            }
        }

        public void bind(String path) {
            lock.lock();
            try {
                acquires++;
                bindI(path);
            } finally {
                lock.unlock();
            }
        }

        // Implementation methods: trust that the lock is held, never take it.
        private String findI(String path) {
            String file = checkCacheI(path);
            if (file == null) {
                bindI(path); // not bind(): that would take the lock again
                file = checkCacheI(path);
            }
            return file;
        }

        private String checkCacheI(String path) {
            return files.get(path);
        }

        private void bindI(String path) {
            files.put(path, "mapped " + path);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        FileCache cache = new FileCache();
        cache.bind("/index.html");
        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++) cache.find(paths[i % 3]);
            });
            threads.add(t);
            t.start();
        }
        for (Thread t : threads) t.join();
        System.out.println("find /a.html: " + cache.find("/a.html"));
        System.out.println("files cached: " + cache.files.size());
        System.out.println("lock acquisitions: " + cache.acquires);
    }
}
Output
find /a.html: mapped /a.html
files cached: 4
lock acquisitions: 4002
  • Verdict: idiom. Public methods take the lock and private methods do the work, so each interface call takes the lock once.
using System;
using System.Collections.Generic;
using System.Threading;

class FileCache
{
    private readonly object gate = new object();
    public readonly Dictionary<string, string> Files = new();
    public int Acquires;

    // Interface methods: take the lock, then call an implementation method.
    public string Find(string path)
    {
        lock (gate)
        {
            Acquires++;
            return FindI(path);
        }
    }

    public void Bind(string path)
    {
        lock (gate)
        {
            Acquires++;
            BindI(path);
        }
    }

    // Implementation methods: trust that the lock is held, never take it.
    private string FindI(string path)
    {
        var file = CheckCacheI(path);
        if (file == null)
        {
            BindI(path); // not Bind(): that would take the lock again
            file = CheckCacheI(path);
        }
        return file!;
    }

    private string? CheckCacheI(string path) => Files.TryGetValue(path, out var file) ? file : null;

    private void BindI(string path) => Files[path] = "mapped " + path;
}

static class Program
{
    static void Main()
    {
        var cache = new FileCache();
        cache.Bind("/index.html");
        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++) cache.Find(paths[i % 3]);
            });
            threads.Add(t);
            t.Start();
        }
        foreach (var t in threads) t.Join();
        Console.WriteLine("find /a.html: " + cache.Find("/a.html"));
        Console.WriteLine("files cached: " + cache.Files.Count);
        Console.WriteLine("lock acquisitions: " + cache.Acquires);
    }
}
Output
find /a.html: mapped /a.html
files cached: 4
lock acquisitions: 4002
  • Verdict: idiom. Public methods take the lock and private methods do the work, so each interface call takes the lock once.
JavaScriptGitHub
// A lock for async 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 {
  lock = new TaskMutex(); // not reentrant
  files = new Map();
  acquires = 0;

  // Interface methods: take the lock, then call an implementation method.
  find(path) {
    return this.lock.run(async () => {
      this.acquires++;
      return this.findI(path);
    });
  }

  bind(path) {
    return this.lock.run(async () => {
      this.acquires++;
      this.bindI(path);
    });
  }

  // Implementation methods: trust that the lock is held, never take it.
  async findI(path) {
    let file = this.checkCacheI(path);
    if (file === undefined) {
      await null; // another task can run here, but it waits for the lock
      this.bindI(path); // not bind(): that would wait for itself
      file = this.checkCacheI(path);
    }
    return file;
  }

  checkCacheI(path) {
    return this.files.get(path);
  }

  bindI(path) {
    this.files.set(path, "mapped " + path);
  }
}

async function main() {
  const cache = new FileCache();
  await cache.bind("/index.html");
  const paths = ["/a.html", "/b.html", "/c.html"];
  const worker = async () => {
    for (let i = 0; i < 1000; i++) await cache.find(paths[i % 3]);
  };
  await Promise.all([worker(), worker(), worker(), worker()]);
  console.log("find /a.html:", await cache.find("/a.html"));
  console.log("files cached:", cache.files.size);
  console.log("lock acquisitions:", cache.acquires);
}

main();
Output
find /a.html: mapped /a.html
files cached: 4
lock acquisitions: 4002
  • Verdict: idiom. The example uses plain methods, so the I suffix marks the implementation methods by convention. The promise lock is not reentrant: a call from findI to find would wait for its own body to end.
TypeScriptGitHub
// A lock for async tasks: each body waits for the one before it.
class TaskMutex {
  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 {
  private lock = new TaskMutex(); // not reentrant
  files = new Map<string, string>();
  acquires = 0;

  // Interface methods: take the lock, then call an implementation method.
  find(path: string): Promise<string> {
    return this.lock.run(async () => {
      this.acquires++;
      return this.findI(path);
    });
  }

  bind(path: string): Promise<void> {
    return this.lock.run(async () => {
      this.acquires++;
      this.bindI(path);
    });
  }

  // Implementation methods: trust that the lock is held, never take it.
  private async findI(path: string): Promise<string> {
    let file = this.checkCacheI(path);
    if (file === undefined) {
      await null; // another task can run here, but it waits for the lock
      this.bindI(path); // not bind(): that would wait for itself
      file = this.checkCacheI(path)!;
    }
    return file;
  }

  private checkCacheI(path: string): string | undefined {
    return this.files.get(path);
  }

  private bindI(path: string): void {
    this.files.set(path, "mapped " + path);
  }
}

async function main(): Promise<void> {
  const cache = new FileCache();
  await cache.bind("/index.html");
  const paths = ["/a.html", "/b.html", "/c.html"];
  const worker = async () => {
    for (let i = 0; i < 1000; i++) await cache.find(paths[i % 3]);
  };
  await Promise.all([worker(), worker(), worker(), worker()]);
  console.log("find /a.html:", await cache.find("/a.html"));
  console.log("files cached:", cache.files.size);
  console.log("lock acquisitions:", cache.acquires);
}

main();
Output
find /a.html: mapped /a.html
files cached: 4
lock acquisitions: 4002
  • Verdict: idiom. private marks the implementation methods for the compiler. The promise lock is not reentrant: a call from findI to find would wait for its own body to end.
package main

import (
	"fmt"
	"sync"
)

type FileCache struct {
	mu       sync.Mutex // not reentrant
	files    map[string]string
	acquires int
}

// Interface methods: take the lock, then call an implementation method.
func (c *FileCache) Find(path string) string {
	c.mu.Lock()
	defer c.mu.Unlock()
	c.acquires++
	return c.findI(path)
}

func (c *FileCache) Bind(path string) {
	c.mu.Lock()
	defer c.mu.Unlock()
	c.acquires++
	c.bindI(path)
}

// Implementation methods: trust that the lock is held, never take it.
func (c *FileCache) findI(path string) string {
	file, ok := c.checkCacheI(path)
	if !ok {
		c.bindI(path) // not Bind: that would take the lock again
		file, _ = c.checkCacheI(path)
	}
	return file
}

func (c *FileCache) checkCacheI(path string) (string, bool) {
	file, ok := c.files[path]
	return file, ok
}

func (c *FileCache) bindI(path string) {
	c.files[path] = "mapped " + path
}

func main() {
	cache := &FileCache{files: map[string]string{}}
	cache.Bind("/index.html")
	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++ {
				cache.Find(paths[i%3])
			}
		}()
	}
	wg.Wait()
	fmt.Println("find /a.html:", cache.Find("/a.html"))
	fmt.Println("files cached:", len(cache.files))
	fmt.Println("lock acquisitions:", cache.acquires)
}
Output
find /a.html: mapped /a.html
files cached: 4
lock acquisitions: 4002
  • Verdict: idiom. Exported methods are the interface methods, and unexported methods are the implementation methods. sync.Mutex is not reentrant, so a call from findI to Find would block.
RustGitHub
use std::collections::HashMap;
use std::sync::Mutex;
use std::thread;

// The state and its implementation methods. They take `&mut self`,
// so they can run only while the caller holds the guard.
struct Inner {
    files: HashMap<String, String>,
    acquires: usize,
}

impl Inner {
    fn find_i(&mut self, path: &str) -> String {
        match self.check_cache_i(path) {
            Some(file) => file,
            None => {
                self.bind_i(path); // the lock is already held
                self.check_cache_i(path).unwrap()
            }
        }
    }

    fn check_cache_i(&self, path: &str) -> Option<String> {
        self.files.get(path).cloned()
    }

    fn bind_i(&mut self, path: &str) {
        self.files.insert(path.to_string(), format!("mapped {path}"));
    }
}

pub struct FileCache {
    lock: Mutex<Inner>,
}

impl FileCache {
    // Interface methods: take the lock, then call an implementation method.
    pub fn find(&self, path: &str) -> String {
        let mut inner = self.lock.lock().unwrap();
        inner.acquires += 1;
        inner.find_i(path)
    }

    pub fn bind(&self, path: &str) {
        let mut inner = self.lock.lock().unwrap();
        inner.acquires += 1;
        inner.bind_i(path);
    }

    fn counts(&self) -> (usize, usize) {
        let inner = self.lock.lock().unwrap();
        (inner.files.len(), inner.acquires)
    }
}

fn main() {
    let cache = FileCache { lock: Mutex::new(Inner { files: HashMap::new(), acquires: 0 }) };
    cache.bind("/index.html");
    let paths = ["/a.html", "/b.html", "/c.html"];
    thread::scope(|s| {
        for _ in 0..4 {
            s.spawn(|| {
                for i in 0..1000 {
                    cache.find(paths[i % 3]);
                }
            });
        }
    });
    println!("find /a.html: {}", cache.find("/a.html"));
    let (files, acquires) = cache.counts();
    println!("files cached: {files}");
    println!("lock acquisitions: {acquires}");
}
Output
find /a.html: mapped /a.html
files cached: 4
lock acquisitions: 4002
  • Verdict: idiom. The implementation methods are on Inner, and the only way to reach an Inner is through the Mutex guard. So the split between the two kinds of method is checked by the compiler.

Consequences

Benefits:1

  • Increased robustness. The pattern ensures that deadlock does not occur due to intra-component method calls.1
  • Enhanced performance. The pattern ensures that no unnecessary locks are acquired or released.1

Liability:1

  • Additional indirection and extra methods. Each interface method requires at least one implementation method. This increases the footprint of the component and may add an extra level of method-call indirection for each invocation. One way to minimize this overhead is to inline each interface method.1

Here is the mistake that the pattern prevents. The public find calls the public bind while it holds a lock that is not reentrant. In this version, bind tries the lock with a timeout, so the program shows the failure instead of waiting forever:

This code runs but gives a wrong answer on purpose.

import threading


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

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

    def find(self, path):
        with self.lock:
            if path not in self.files:
                return self.bind(path)  # an interface method calls an interface method
            return self.files[path]


cache = FileCache()
print("find /a.html:", cache.find("/a.html"))
print("files cached:", len(cache.files))
Output
find /a.html: self-deadlock
files cached: 0

When not to use it

  • The component has one method, or its methods never call each other. There is no intra-component call to protect, and the extra methods only add size.1
  • The component must take the lock for each step separately, for example to let other threads run between two steps. The pattern holds the lock for the whole interface call.
  • Each step is a single atomic operation on a type that is safe for concurrent use. No component lock is needed then.
  • Recursive lock. The other answer to self-deadlock is a recursive lock. A reentrant lock may be acquired multiple times by the same thread, so the call does not block, but the overhead of the second acquisition stays.21
  • Strategized Locking. Components designed according to the Strategized Locking pattern 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
  • Scoped Locking. The interface methods in the paper use the Scoped Locking idiom to acquire and release the lock.1
  • Decorator. The pattern is related to Decorator, which extends an object transparently by dynamically attaching additional responsibilities. The primary difference is that Decorator focuses on objects, whereas Thread-safe Interface focuses on classes.1
  • Synchronization patterns. POSA2 puts Thread-Safe Interface with Scoped Locking, Strategized Locking and Double-Checked Locking Optimization.3

This program counts the lock acquisitions of both answers for the same four lookups, of which three are misses. The recursive design takes the lock again in each bind:

import threading


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

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

    def __exit__(self, *exc):
        self.inner.release()


class RecursiveCache:
    """Every method locks; a recursive lock avoids the self-deadlock."""

    def __init__(self):
        self.lock = CountingLock(threading.RLock())
        self.files = {}

    def bind(self, path):
        with self.lock:
            self.files[path] = "mapped " + path

    def find(self, path):
        with self.lock:
            if path not in self.files:
                self.bind(path)  # locks a second time
            return self.files[path]


class InterfaceCache:
    """Thread-Safe Interface: only the public methods lock."""

    def __init__(self):
        self.lock = CountingLock(threading.Lock())
        self.files = {}

    def bind(self, path):
        with self.lock:
            self._bind_i(path)

    def find(self, path):
        with self.lock:
            if path not in self.files:
                self._bind_i(path)
            return self.files[path]

    def _bind_i(self, path):
        self.files[path] = "mapped " + path


for cache in [RecursiveCache(), InterfaceCache()]:
    for path in ["/a.html", "/b.html", "/c.html", "/a.html"]:
        cache.find(path)
    print(f"{type(cache).__name__}: 4 finds, {cache.lock.acquires} lock acquisitions")
Output
RecursiveCache: 4 finds, 7 lock acquisitions
InterfaceCache: 4 finds, 4 lock acquisitions

Known uses

  • ACE. The pattern is used extensively throughout the ACE object-oriented network programming toolkit.1
  • Python queue. Queue uses a threading.Lock as its mutex. Its public put and get methods acquire the mutex through conditions that share it, and the methods that subclasses override, such as _put and _get, will only be called with appropriate locks held.4

References

  1. Douglas C. Schmidt, Strategized Locking, Thread-safe Interface, and Scoped Locking: Patterns and Idioms for Simplifying Multi-threaded C++ Components (C++ Report), 3 The Thread-safe Interface Pattern, sections 3.1 to 3.9
  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. Lib/queue.py, CPython source code, class Queue, __init__ and the _qsize, _put and _get methods

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