Skip to content

Atomic Batches

The Course
•
25 min study

Intermediate's importer deliberately kept successful records before a bad one. Sometimes the required policy is the opposite: either accept an entire batch or leave existing state unchanged. Staging a candidate state makes that all-or-nothing contract explicit in a small in-memory program.

Understand the contract

Start by copying the current map into a private candidate. Apply each proposed change to that candidate and validate conflicts there. Only when the complete batch succeeds does the owner replace its current map. If a later entry fails, the local candidate is discarded and the original state stays intact.

Checking only against the old map is insufficient: two new entries in the same batch can conflict with each other. Each accepted candidate entry must become visible to later validations in that same candidate. The example uses immutable strings, so a shallow map copy isolates every relevant change. With mutable values, changing a shared object's fields could still leak out of staging.

“Atomic” here describes the observable contract of one synchronous call in this single-threaded model. Copy-and-swap is not automatically thread-safe, durable, or crash-safe. A database transaction and a lock solve additional problems. We will test this policy with deterministic examples instead of pretending the browser engine executes concurrent threads.

Before running, write the output you expect and explain which rule produces each line. Each editor is an independent program.

Predict, then run Java
import java.util.Map;
import java.util.LinkedHashMap;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        Map<String, String> current = new LinkedHashMap<>();
        current.put("A", "Read");
        Map<String, String> next = stage(current, List.of("B", "C"));
        System.out.println(current.keySet());
        System.out.println(next.keySet());
    }

    static Map<String, String> stage(Map<String, String> current, List<String> ids) {
        Map<String, String> candidate = new LinkedHashMap<>(current);
        for (String id : ids) {
            if (candidate.containsKey(id)) {
                throw new IllegalArgumentException("duplicate id");
            }
            candidate.put(id, "New");
        }
        return candidate;
    }
}
Check your prediction
Text
[A]
[A, B, C]

Trace a different case

A failure after one valid candidate insertion is the important case. Testing only an immediately invalid first entry would also pass for an implementation that mutates the real map incrementally. The existing map below must still contain only A after B is followed by a conflicting A. The caller assigns the returned map only on success.

Compare the boundary case Java
import java.util.Map;
import java.util.LinkedHashMap;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        Map<String, String> current = new LinkedHashMap<>();
        current.put("A", "Read");
        try {
            current = stage(current, List.of("B", "A"));
        } catch (IllegalArgumentException expected) {
            System.out.println("Batch rejected");
        }
        System.out.println(current.keySet());
    }

    static Map<String, String> stage(Map<String, String> current, List<String> ids) {
        Map<String, String> candidate = new LinkedHashMap<>(current);
        for (String id : ids) {
            if (candidate.containsKey(id)) {
                throw new IllegalArgumentException("duplicate id");
            }
            candidate.put(id, "New");
        }
        return candidate;
    }
}
Check your prediction
Text
Batch rejected
[A]

Locate the last safe point before publishing

Staging works because candidate state remains private until every required check succeeds. A later error discards the candidate. If an element object is shared and mutable, changing one of its fields can leak through both maps even when their containers are separate. Copying is sufficient here because the values are immutable.

Test a successful first candidate update followed by a conflict. Also test two conflicting new IDs within the same batch, which requires validating against the candidate rather than only old state. An immediately bad first row is weaker evidence of rollback.

The commit point should be easy to point at in the implementation. In a synchronous single-threaded call, replacing the owned reference after validation gives the required observable policy. Concurrency, durable storage and crash recovery add guarantees that this copy alone cannot establish.

Debug a plausible mistake

The catch already runs, so observing a rejection message cannot diagnose this bug. The important evidence is the original map after an earlier candidate entry was accepted. Aliasing lets changes escape before the supposed commit point.

Exercise

Repair a late rejected batch

Rejecting the later A must leave current exactly {A=10}; no B may leak into it. Print Rejected, then {A=10}. Also test a valid [B,C] batch by explicitly assigning its returned candidate in the caller. Predict what the current program actually prints before changing it. Make the smallest justified repair. The supplied version compiles; its behavior is the problem.

Debugging workspace Java
import java.util.Map;
import java.util.LinkedHashMap;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> current = new LinkedHashMap<>();
        current.put("A", 10);
        try {
            stage(current, List.of("B", "A"));
        } catch (IllegalArgumentException expected) {
            System.out.println("Rejected");
        }
        System.out.println(current);
    }

    static Map<String, Integer> stage(Map<String, Integer> current, List<String> ids) {
        Map<String, Integer> candidate = current;
        for (String id : ids) {
            if (candidate.containsKey(id)) {
                throw new IllegalArgumentException("duplicate");
            }
            candidate.put(id, 20);
        }
        return candidate;
    }
}
Hint 1: the idea

Staging requires a separate container while values remain safe to share.

Hint 2: a first step

Copy current when constructing candidate; catching a later failure cannot undo an alias mutation.

Show one solution
Java
import java.util.Map;
import java.util.LinkedHashMap;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> current = new LinkedHashMap<>();
        current.put("A", 10);
        try {
            stage(current, List.of("B", "A"));
        } catch (IllegalArgumentException expected) {
            System.out.println("Rejected");
        }
        System.out.println(current);
    }

    static Map<String, Integer> stage(Map<String, Integer> current, List<String> ids) {
        Map<String, Integer> candidate = new LinkedHashMap<>(current);
        for (String id : ids) {
            if (candidate.containsKey(id)) {
                throw new IllegalArgumentException("duplicate");
            }
            candidate.put(id, 20);
        }
        return candidate;
    }
}

Expected output after repair:

Text
Rejected
{A=10}

The bug was that stage wrote into current directly, so B was already stored when the duplicate A threw. The repair copies current into candidate, works only on the copy, and returns it; an exception simply abandons the copy. The valid [B,C] batch proves the other half of the contract: the caller sees the new state only by assigning the returned map.

Build it yourself

Exercise

Atomic Batches: practice

Write appendUnique(List<String> current, List<String> additions) returning a new unmodifiable list only if all entries remain unique. Inputs and elements are nonnull; current is already unique. Preserve order. Demonstrate [A] + [B,C] gives [A,B,C], but [A] + [B,B] rejects and leaves [A] unchanged. Use a Set to track candidate membership.

Your workspace Java
public class Main {
    public static void main(String[] args) {
        // Add your implementation and checks below.
        System.out.println("Your workspace");
    }
}
Hint 1: the idea

Validation must include entries already staged from the same batch, not only entries in the original list.

Hint 2: a first step

Build a candidate list and membership set locally; publish List.copyOf only after the loop.

Show one solution
Java
import java.util.List;
import java.util.ArrayList;
import java.util.Set;
import java.util.HashSet;

public class Main {
    public static void main(String[] args) {
        List<String> current = List.of("A");
        System.out.println(appendUnique(current, List.of("B", "C")));
        try {
            appendUnique(current, List.of("B", "B"));
            throw new AssertionError("duplicate accepted");
        } catch (IllegalArgumentException expected) {
            System.out.println(current);
        }
    }

    static List<String> appendUnique(List<String> current, List<String> additions) {
        List<String> candidate = new ArrayList<>(current);
        Set<String> seen = new HashSet<>(current);
        for (String id : additions) {
            if (!seen.add(id)) {
                throw new IllegalArgumentException("duplicate id");
            }
            candidate.add(id);
        }
        return List.copyOf(candidate);
    }
}

Expected output:

Text
[A, B, C]
[A]

Both the list and the set start as copies of current, so a duplicate anywhere, including against an existing entry, is caught by seen.add returning false. The method throws before returning anything, and current was never touched, so the rejected batch leaves [A]. List.copyOf makes the success result unmodifiable, so a caller cannot change it behind the method's back.

Change it and test again

Test empty additions and a conflict with existing A after a new B. Deliberately use current instead of candidate for the duplicate test and find the within-batch case that exposes it. Then describe what would change if additions were mutable objects and staging called setters on them.

Explain before moving on

Compare recover-per-line and all-or-nothing policies: neither is universally correct. Which does your caller expect? Identify the exact commit point and explain why a catch block alone cannot undo changes made before it.

Was this article helpful?

Your response is saved on this device.