Video in progress

Is it safe to give a HashMap that is built once and then only read to several threads without synchronization? Under what conditions?

class RoutingTable {
    private Map<String, Route> routes = new HashMap<>();

    void reload(List<Route> fresh) {
        Map<String, Route> m = new HashMap<>();
        for (Route r : fresh) m.put(r.path(), r);
        routes = m;
    }

    Route find(String path) { return routes.get(path); }
}

Yes, if the map is safely published after it is fully built (a final field, volatile, a concurrent collection, or thread start) and nobody modifies it afterwards. If it is handed over by writing to a plain field, another thread may see a half-built state.

📖 Answer

In this code reload uses the right idea: it builds the new map locally and swaps the reference. But routes is a plain field. According to the Java Memory Model, another thread in find:

  • may never see the new reference (the JIT keeps the value in a register);
  • or may see the new reference but with the table and Node fields inside the map not yet fully written, because there is no happens-before relationship.

In practice this is rarely visible on x86, but on ARM servers (Graviton) the probability goes up. Bugs like this go undiscovered for months.

The fix is safe publication:

private volatile Map<String, Route> routes = Map.of();

void reload(List<Route> fresh) {
    routes = fresh.stream().collect(
            Collectors.toUnmodifiableMap(Route::path, r -> r));
}

A volatile write makes all the writes before it (building the map) visible to the thread that reads it. Since the map is immutable, nobody can accidentally modify it later, and that is the second condition.

Other safe publication methods: a final field filled in the constructor (provided this doesn't escape the constructor), AtomicReference, putting it into a ConcurrentHashMap, and Thread.start() or submitting to an executor after creating the map.

From an architecture point of view, this is the "copy-on-write snapshot" pattern: configuration, routing, feature flags, permission tables. Reads are lock-free and fast, and updates are rare. I give teams this as a small shared component (Snapshot<T>), so that nobody has to remember volatile on their own.