Programming Search⌘K

Patterncore

Copy-on-write

Also called copy-on-write, cow, implicit sharing, shadowing, clone-on-write.

Copy-on-write shares one copy of data among its users until one of them writes. The writer makes a private copy and changes that, so readers keep a stable snapshot and need no lock.

Family
concurrency
Intent
Share data between users until one of them tries to modify it, and make a copy only then, so that each writer gets its own version and the readers are unaffected.
Also called
Implicit sharing, Shadowing

Intent

Copy-on-write shares the same data between users until one tries to modify it.1 If no changes are made, no private copy is created. A copy is only made when needed, so that each user has its own version when it modifies the data.1

Problem

A list of listeners is read by many threads and changed only now and then. A thread that iterates over the list while another thread adds an item can fail or see a half-changed list. A lock around each iteration makes the readers wait for each other and for the writer, although reads are almost all of the work. A copy of the list for each reader wastes time and memory, because most readers never change it.

Solution

Let all users share one copy. A writer does not change the shared copy: it makes a fresh copy, changes the copy, and then makes the copy the shared one. A reader takes a reference to the current copy and uses it with no lock. The copy it holds never changes.

Java's CopyOnWriteArrayList works this way. All mutative operations, such as add and set, are implemented by making a fresh copy of the underlying array.2 Its iterator uses a reference to the state of the array at the point that the iterator was created. That array never changes during the lifetime of the iterator, so interference is impossible.2

before:  readers A, B --> [l0]
add(l1): writer copies     [l0] -> [l0, l1], then publishes it
after:   reader A (old)  --> [l0]          still a valid snapshot
         reader C (new)  --> [l0, l1]

Example

The example keeps a list of listeners as a tuple that never changes. 4 readers iterate over the current snapshot 1000 times each with no lock, while a writer adds 100 listeners. Each add copies the tuple under a lock that only writers take.

iterations: 4000
iterations that failed: 0
listeners at the end: 101
length of the first snapshot: 1

The examples for each language show the same program.

PythonGitHub
import threading


class CopyOnWriteList:
    def __init__(self, items=()):
        self._items = tuple(items)  # never changed in place
        self._write_lock = threading.Lock()  # writers only

    def add(self, item):
        with self._write_lock:
            self._items = self._items + (item,)  # copy, then publish

    def snapshot(self):
        return self._items  # readers take no lock


listeners = CopyOnWriteList(["listener 0"])
first = listeners.snapshot()
iterations = 0
errors = 0
count_lock = threading.Lock()  # only for the counters of the demo


def reader():
    global iterations, errors
    for _ in range(1000):
        try:
            for name in listeners.snapshot():
                pass  # call each listener
        except RuntimeError:
            with count_lock:
                errors += 1
        with count_lock:
            iterations += 1


def writer():
    for n in range(1, 101):
        listeners.add(f"listener {n}")


threads = [threading.Thread(target=reader) for _ in range(4)] + [threading.Thread(target=writer)]
for t in threads:
    t.start()
for t in threads:
    t.join()
print("iterations:", iterations)
print("iterations that failed:", errors)
print("listeners at the end:", len(listeners.snapshot()))
print("length of the first snapshot:", len(first))
Output
iterations: 4000
iterations that failed: 0
listeners at the end: 101
length of the first snapshot: 1
  • Verdict: idiom. CopyOnWriteList is a small class: the items are a tuple that never changes, and add builds a new tuple under a lock that only writers take.
#include <atomic>
#include <iostream>
#include <memory>
#include <mutex>
#include <string>
#include <thread>
#include <vector>

class CopyOnWriteList {
public:
    explicit CopyOnWriteList(std::vector<std::string> items)
        : items_(std::make_shared<const std::vector<std::string>>(std::move(items))) {}

    void add(const std::string& item) {
        std::lock_guard<std::mutex> write(write_mutex_); // writers only
        auto next = std::make_shared<std::vector<std::string>>(*snapshot()); // copy
        next->push_back(item); // change the copy
        std::lock_guard<std::mutex> lock(pointer_mutex_);
        items_ = std::move(next); // publish it
    }

    std::shared_ptr<const std::vector<std::string>> snapshot() const {
        std::lock_guard<std::mutex> lock(pointer_mutex_); // guards only the pointer copy
        return items_;
    }

private:
    std::shared_ptr<const std::vector<std::string>> items_;
    std::mutex write_mutex_;
    mutable std::mutex pointer_mutex_;
};

int main() {
    CopyOnWriteList listeners({"listener 0"});
    auto first = listeners.snapshot();
    std::atomic<int> iterations{0}, errors{0};
    std::vector<std::thread> threads;
    for (int i = 0; i < 4; i++) {
        threads.emplace_back([&] {
            for (int r = 0; r < 1000; r++) {
                auto items = listeners.snapshot();
                for (const auto& name : *items) {
                    (void)name; // call each listener
                }
                iterations++;
            }
        });
    }
    threads.emplace_back([&] {
        for (int n = 1; n <= 100; n++) listeners.add("listener " + std::to_string(n));
    });
    for (auto& t : threads) t.join();
    std::cout << "iterations: " << iterations << "\n";
    std::cout << "iterations that failed: " << errors << "\n";
    std::cout << "listeners at the end: " << listeners.snapshot()->size() << "\n";
    std::cout << "length of the first snapshot: " << first->size() << "\n";
}
Output
iterations: 4000
iterations that failed: 0
listeners at the end: 101
length of the first snapshot: 1
  • Verdict: idiom. CopyOnWriteList keeps a std::shared_ptr to a const vector; add copies the vector and swaps the pointer, and a reader keeps its old vector alive while it iterates.
JavaGitHub
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        CopyOnWriteArrayList<String> listeners = new CopyOnWriteArrayList<>(List.of("listener 0"));
        List<String> first = new ArrayList<>();
        for (String name : listeners) first.add(name); // iterate over the first snapshot
        AtomicInteger iterations = new AtomicInteger();
        AtomicInteger errors = new AtomicInteger();
        List<Thread> threads = new ArrayList<>();
        for (int i = 0; i < 4; i++) {
            threads.add(new Thread(() -> {
                for (int r = 0; r < 1000; r++) {
                    try {
                        for (String name : listeners) {
                            // call each listener
                        }
                    } catch (ConcurrentModificationException e) {
                        errors.incrementAndGet();
                    }
                    iterations.incrementAndGet();
                }
            }));
        }
        threads.add(new Thread(() -> {
            for (int n = 1; n <= 100; n++) listeners.add("listener " + n); // copies the array
        }));
        for (Thread t : threads) t.start();
        for (Thread t : threads) t.join();
        System.out.println("iterations: " + iterations.get());
        System.out.println("iterations that failed: " + errors.get());
        System.out.println("listeners at the end: " + listeners.size());
        System.out.println("length of the first snapshot: " + first.size());
    }
}
Output
iterations: 4000
iterations that failed: 0
listeners at the end: 101
length of the first snapshot: 1
  • Verdict: stdlib. CopyOnWriteArrayList copies its array on each add, and each for loop iterates over the snapshot from the moment the loop started.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;

class Program
{
    static ImmutableList<string> listeners = ImmutableList.Create("listener 0");
    static readonly object writeLock = new object(); // writers only

    static void Main()
    {
        var first = Volatile.Read(ref listeners);
        int iterations = 0, errors = 0;
        var threads = new List<Thread>();
        for (int i = 0; i < 4; i++)
        {
            threads.Add(new Thread(() =>
            {
                for (int r = 0; r < 1000; r++)
                {
                    try
                    {
                        foreach (var name in Volatile.Read(ref listeners))
                        {
                            // call each listener
                        }
                    }
                    catch (InvalidOperationException)
                    {
                        Interlocked.Increment(ref errors);
                    }
                    Interlocked.Increment(ref iterations);
                }
            }));
        }
        threads.Add(new Thread(() =>
        {
            for (int n = 1; n <= 100; n++)
            {
                lock (writeLock)
                {
                    Volatile.Write(ref listeners, listeners.Add("listener " + n)); // a new list
                }
            }
        }));
        foreach (var t in threads) t.Start();
        foreach (var t in threads) t.Join();
        Console.WriteLine("iterations: " + iterations);
        Console.WriteLine("iterations that failed: " + errors);
        Console.WriteLine("listeners at the end: " + listeners.Count);
        Console.WriteLine("length of the first snapshot: " + first.Count);
    }
}
Output
iterations: 4000
iterations that failed: 0
listeners at the end: 101
length of the first snapshot: 1
  • Verdict: stdlib. ImmutableList.Add returns a new list and leaves the old one as it was; the writer publishes the new list with Volatile.Write under a lock that only writers take.
JavaScriptGitHub
class CopyOnWriteList {
  constructor(items) {
    this.items = Object.freeze([...items]); // never changed in place
  }

  add(item) {
    this.items = Object.freeze([...this.items, item]); // copy, then publish
  }

  snapshot() {
    return this.items;
  }
}

const listeners = new CopyOnWriteList(["listener 0"]);
const first = listeners.snapshot();
let iterations = 0;
let errors = 0;
const tick = () => new Promise((resolve) => setImmediate(resolve));

async function reader() {
  for (let r = 0; r < 1000; r++) {
    try {
      for (const name of listeners.snapshot()) {
        if (name === "listener 0") await tick(); // the writer can run mid-loop
      }
    } catch (e) {
      errors += 1;
    }
    iterations += 1;
  }
}

async function writer() {
  for (let n = 1; n <= 100; n++) {
    listeners.add(`listener ${n}`);
    await tick();
  }
}

Promise.all([reader(), reader(), reader(), reader(), writer()]).then(() => {
  console.log("iterations:", iterations);
  console.log("iterations that failed:", errors);
  console.log("listeners at the end:", listeners.snapshot().length);
  console.log("length of the first snapshot:", first.length);
});
Output
iterations: 4000
iterations that failed: 0
listeners at the end: 101
length of the first snapshot: 1
  • Verdict: idiom. CopyOnWriteList replaces a frozen array on each add, and a reader that awaits inside its loop keeps iterating over the array it started with.
TypeScriptGitHub
class CopyOnWriteList {
  private items: readonly string[];

  constructor(items: string[]) {
    this.items = Object.freeze([...items]); // never changed in place
  }

  add(item: string): void {
    this.items = Object.freeze([...this.items, item]); // copy, then publish
  }

  snapshot(): readonly string[] {
    return this.items;
  }
}

const listeners = new CopyOnWriteList(["listener 0"]);
const first = listeners.snapshot();
let iterations = 0;
let errors = 0;
const tick = (): Promise<void> => new Promise((resolve) => setImmediate(resolve));

async function reader(): Promise<void> {
  for (let r = 0; r < 1000; r++) {
    try {
      for (const name of listeners.snapshot()) {
        if (name === "listener 0") await tick(); // the writer can run mid-loop
      }
    } catch (e) {
      errors += 1;
    }
    iterations += 1;
  }
}

async function writer(): Promise<void> {
  for (let n = 1; n <= 100; n++) {
    listeners.add(`listener ${n}`);
    await tick();
  }
}

Promise.all([reader(), reader(), reader(), reader(), writer()]).then(() => {
  console.log("iterations:", iterations);
  console.log("iterations that failed:", errors);
  console.log("listeners at the end:", listeners.snapshot().length);
  console.log("length of the first snapshot:", first.length);
});
Output
iterations: 4000
iterations that failed: 0
listeners at the end: 101
length of the first snapshot: 1
  • Verdict: idiom. CopyOnWriteList replaces a frozen array on each add, and a reader that awaits inside its loop keeps iterating over the array it started with.
package main

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

// CopyOnWriteList keeps a slice that is never changed after it is published.
type CopyOnWriteList struct {
	items     atomic.Pointer[[]string]
	writeLock sync.Mutex // writers only
}

func (l *CopyOnWriteList) Add(item string) {
	l.writeLock.Lock()
	defer l.writeLock.Unlock()
	old := *l.items.Load()
	next := make([]string, len(old), len(old)+1)
	copy(next, old) // copy, then change the copy
	next = append(next, item)
	l.items.Store(&next)
}

func (l *CopyOnWriteList) Snapshot() []string { return *l.items.Load() }

func main() {
	listeners := &CopyOnWriteList{}
	initial := []string{"listener 0"}
	listeners.items.Store(&initial)
	first := listeners.Snapshot()
	var iterations, errors atomic.Int64
	var wg sync.WaitGroup
	for i := 0; i < 4; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			for r := 0; r < 1000; r++ {
				for range listeners.Snapshot() {
					// call each listener
				}
				iterations.Add(1)
			}
		}()
	}
	wg.Add(1)
	go func() {
		defer wg.Done()
		for n := 1; n <= 100; n++ {
			listeners.Add("listener " + strconv.Itoa(n))
		}
	}()
	wg.Wait()
	fmt.Println("iterations:", iterations.Load())
	fmt.Println("iterations that failed:", errors.Load())
	fmt.Println("listeners at the end:", len(listeners.Snapshot()))
	fmt.Println("length of the first snapshot:", len(first))
}
Output
iterations: 4000
iterations that failed: 0
listeners at the end: 101
length of the first snapshot: 1
  • Verdict: idiom. CopyOnWriteList copies the slice in Add and publishes the copy with atomic.Pointer; a range loop over a snapshot cannot fail, so errors stays 0.
RustGitHub
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::thread;

struct CopyOnWriteList {
    items: Mutex<Arc<Vec<String>>>, // guards only the pointer
}

impl CopyOnWriteList {
    fn add(&self, item: String) {
        let mut current = self.items.lock().unwrap();
        let mut next = Vec::clone(&current); // copy
        next.push(item); // change the copy
        *current = Arc::new(next); // publish it
    }

    fn snapshot(&self) -> Arc<Vec<String>> {
        Arc::clone(&self.items.lock().unwrap())
    }
}

fn main() {
    let listeners = Arc::new(CopyOnWriteList {
        items: Mutex::new(Arc::new(vec!["listener 0".to_string()])),
    });
    let first = listeners.snapshot();
    let iterations = Arc::new(AtomicUsize::new(0));
    let errors = AtomicUsize::new(0);
    let mut threads = Vec::new();
    for _ in 0..4 {
        let (listeners, iterations) = (Arc::clone(&listeners), Arc::clone(&iterations));
        threads.push(thread::spawn(move || {
            for _ in 0..1000 {
                for _name in listeners.snapshot().iter() {
                    // call each listener; the lock is not held here
                }
                iterations.fetch_add(1, Ordering::SeqCst);
            }
        }));
    }
    {
        let listeners = Arc::clone(&listeners);
        threads.push(thread::spawn(move || {
            for n in 1..=100 {
                listeners.add(format!("listener {}", n));
            }
        }));
    }
    for t in threads {
        t.join().unwrap();
    }
    println!("iterations: {}", iterations.load(Ordering::SeqCst));
    println!("iterations that failed: {}", errors.load(Ordering::SeqCst));
    println!("listeners at the end: {}", listeners.snapshot().len());
    println!("length of the first snapshot: {}", first.len());
}
Output
iterations: 4000
iterations that failed: 0
listeners at the end: 101
length of the first snapshot: 1
  • Verdict: idiom. CopyOnWriteList keeps an Arc<Vec<String>>; add clones the vector and replaces the Arc, and a reader holds its own Arc to the old vector while it iterates.

Consequences

Benefits:

  • Readers need no lock, and a snapshot iterator is guaranteed not to throw ConcurrentModificationException.2
  • Data that is never changed is never copied, which saves resources.1
  • The approach is useful when the program cannot or does not want to synchronize traversals, yet needs to preclude interference among concurrent threads.2

Liabilities:

  • Each write copies the whole structure. The Java documentation calls this ordinarily too costly, and more efficient than alternatives only when traversal operations vastly outnumber mutations.2
  • A snapshot is out of date. The iterator does not reflect additions, removals or changes to the list since it was created.2
  • Writers still need a lock or an atomic compare-and-swap, so that two writers do not both copy the same old version and lose one change.

Without the copy, a reader that iterates over a shared dictionary fails when another thread adds an item:

This code runs but gives a wrong answer on purpose.

import threading

listeners = {"listener 0": True, "listener 1": True}  # shared and changed in place
first_seen = threading.Event()
added = threading.Event()


def writer():
    first_seen.wait()
    listeners["listener 2"] = True  # changes the dict during the iteration
    added.set()


t = threading.Thread(target=writer)
t.start()
try:
    for name in listeners:
        first_seen.set()
        added.wait()
except RuntimeError as e:
    print("reader:", e)
t.join()
Output
reader: dictionary changed size during iteration

When not to use it

Do not use copy-on-write for data that changes often or that is large and changes in small steps. Every change then pays for a full copy. A read-write lock or a concurrent collection fits such data better. Do not use it when every reader must see the latest value at once, because a reader can hold an old snapshot.

  • Clone-on-write in one thread. Rust's Cow type can enclose borrowed data and provide immutable access to it, and clone the data lazily when mutation or ownership is required.3 Rc::make_mut and Arc::make_mut give clone-on-write for reference-counted pointers.3 The example returns its input when nothing changes and copies it at the first write:
copies = 0


def without_negatives(items):
    """Return items itself if nothing changes, else a changed copy."""
    global copies
    result = items
    for i, x in enumerate(items):
        if x < 0:
            if result is items:  # the first write makes the copy
                result = list(items)
                copies += 1
            result[i] = -x
    return result


calls = [[1, 2, 3], [4, -5, 6], [7, 8]]
outputs = [without_negatives(c) for c in calls]
print("outputs:", outputs)
print("copies made:", copies, "of", len(calls), "calls")
print("first call returned its own list:", outputs[0] is calls[0])
Output
outputs: [[1, 2, 3], [4, 5, 6], [7, 8]]
copies made: 1 of 3 calls
first call returned its own list: True
  • Virtual memory. The fork() system call shares the physical pages of the parent with the child. The kernel marks the pages read-only and, when one process writes to a page, allocates a new physical page for it.1
  • Storage. In a copy-on-write file system, a change writes only the affected blocks to new locations and updates the metadata to point to them. This enables snapshots.1

An Immutable object is the shared copy: copy-on-write is the rule for how a writer makes the next one. Qt types that are implicitly shared use atomic compare-and-swap operations on their reference counter.1

Known uses

  • Java: CopyOnWriteArrayList.2
  • Rust: std::borrow::Cow, Rc::make_mut and Arc::make_mut.3
  • Qt: many types are copy-on-write, "implicitly shared" in Qt's terms.1
  • PHP implements all types except references as copy-on-write.1
  • The file systems ZFS, Btrfs, ReFS, APFS and Bcachefs, and Docker image layers.1

References

  1. Copy-on-write, Wikipedia, lead; In virtual memory management; In software; In computer storage
  2. CopyOnWriteArrayList, Java SE 21 API documentation, class description
  3. Enum Cow, Rust standard library documentation, description

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