Skip to lesson

Normal collections under many threads

A class is thread-safe when it keeps working correctly while many threads call its methods at the same time, with no extra locking by the caller. ArrayList, HashMap, HashSet and the other everyday collections are not thread-safe: they were built for one thread at a time, and sharing them between threads gives wrong sizes, lost data and strange exceptions.

ArrayList losing items or throwing

A thread-safe collection stays correct when several threads use it at the same time: no lost items, no broken internal state, no matter how the threads interleave.

ArrayList.add is not one step. It checks whether the inner array is full (and grows it if so), writes the item at position size, and then adds 1 to size. Another thread can run in between any of these steps.

Example 1 · Two threads adding to one ArrayList

ArrayListRaceDemo.javaJava
import java.util.ArrayList;import java.util.List;
public class ArrayListRaceDemo {    public static void main(String[] args) throws InterruptedException {        for (int round = 1; round <= 3; round++) {            List<Integer> tickets = new ArrayList<>();   // shared, not thread-safe
            Runnable bookTickets = () -> {                try {                    for (int i = 0; i < 100_000; i++) {                        tickets.add(i);                    }                } catch (RuntimeException e) {                    System.out.println("  " + Thread.currentThread().getName()                            + " crashed: " + e.getClass().getSimpleName());                }            };
            Thread t1 = new Thread(bookTickets, "counter-1");            Thread t2 = new Thread(bookTickets, "counter-2");            t1.start();            t2.start();            t1.join();            t2.join();
            System.out.println("Round " + round + ": size = " + tickets.size() + " (expected 200000)");        }    }}
Sample output
Round 1: size = 144888 (expected 200000)
  counter-1 crashed: ArrayIndexOutOfBoundsException
Round 2: size = 100161 (expected 200000)
  counter-1 crashed: ArrayIndexOutOfBoundsException
Round 3: size = 100009 (expected 200000)

What this code does

  • Each round, two threads add 100,000 ticket numbers to one shared ArrayList. The size is almost never 200,000: items were written into the same slot and lost.
  • In some rounds a thread also dies with ArrayIndexOutOfBoundsException, because the other thread grew the array in the middle of its write. The numbers and the crashes change on every run.

If two threads read the same size, both write into the same slot and one item is lost. If one thread grows the array while the other is writing, a write can land past the end of the old array, and the thread dies with ArrayIndexOutOfBoundsException. The result changes from run to run, and a small test may even pass. That is exactly what makes this bug dangerous: it hides until the app is busy, for example during an IRCTC Tatkal rush.

HashMap corrupted by concurrent puts

A HashMap keeps its entries in an array of buckets (slots chosen by the key's hash code).

Example 2 · A result server storing marks in a HashMap

HashMapRaceDemo.javaJava
import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;
public class HashMapRaceDemo {    public static void main(String[] args) throws InterruptedException {        Map<Integer, String> results = new HashMap<>();   // roll number -> grade        List<Thread> servers = new ArrayList<>();
        for (int s = 0; s < 4; s++) {            int first = s * 25_000;                         // each thread owns different keys            Thread t = new Thread(() -> {                try {                    for (int roll = first; roll < first + 25_000; roll++) {                        results.put(roll, "PASS");                    }                } catch (RuntimeException e) {                    System.out.println(Thread.currentThread().getName()                            + " crashed: " + e.getClass().getSimpleName());                }            }, "server-" + (s + 1));            t.setDaemon(true);            servers.add(t);            t.start();        }
        long deadline = System.currentTimeMillis() + 2000;  // wait at most 2 seconds in total        int stuck = 0;        for (Thread t : servers) {            t.join(Math.max(1, deadline - System.currentTimeMillis()));            if (t.isAlive()) {                stuck++;            }        }
        System.out.println("Results stored: " + results.size() + " (expected 100000)");        if (stuck > 0) {            System.out.println(stuck + " thread(s) still running after the timeout: stuck in a loop");        }    }}
Sample output
Results stored: 98189 (expected 100000)

What this code does

  • Four threads store 25,000 different roll numbers each, yet results go missing. The number changes from run to run.
  • On some runs a thread crashes with ClassCastException from deep inside HashMap, or gets stuck in a loop in the broken inner links. The threads are daemon threads and main waits at most 2 seconds, so the program always ends.

put finds the bucket, links in a new entry, adds 1 to a size counter and, when the map gets too full, resizes: it builds a bigger array and moves every entry into it.

Two threads doing put at the same time can overwrite each other's entry, lose entries while a resize is moving them, or leave the inner links in a broken shape. Using different keys in each thread does not help, because all threads still share the bucket array and the size counter. In Java 7 and earlier, a concurrent resize could link entries in a circle, so a later get looped forever at 100% CPU. Java 8 changed the resize code, so that classic loop is gone, but the map is still unsafe: entries vanish, size() is wrong, and on some runs a thread crashes or gets stuck, as Example 2 shows.

Find the bug

Find the unsafe shared collection

Each snippet is shared by several threads. Tap the unsafe line, then check the fix.

Two threads add bills to one list.

Round 1 of 3
A broken HashMap usually does not throw an exception at the point of damage. You find out later, when a result that was stored is simply missing.

ConcurrentModificationException

A ConcurrentModificationException (CME) is thrown by a collection's iterator when the collection is structurally changed (an item added or removed) while the loop is running, by anything other than the iterator itself.

Example 3 · CME with only one thread

CmeOneThreadDemo.javaJava
import java.util.ArrayList;import java.util.ConcurrentModificationException;import java.util.List;
public class CmeOneThreadDemo {    public static void main(String[] args) {        List<String> hostel = new ArrayList<>(List.of("Asha", "Bala", "Chirag", "Divya"));
        try {            for (String name : hostel) {                if (name.equals("Bala")) {                    hostel.remove(name);          // changes the list during the loop                }            }        } catch (ConcurrentModificationException e) {            System.out.println("Caught: " + e.getClass().getSimpleName());        }        System.out.println("After the loop: " + hostel);
        List<String> fixed = new ArrayList<>(List.of("Asha", "Bala", "Chirag", "Divya"));        fixed.removeIf(name -> name.equals("Bala"));   // the safe way        System.out.println("With removeIf:  " + fixed);    }}
Output
Caught: ConcurrentModificationException
After the loop: [Asha, Chirag, Divya]
With removeIf:  [Asha, Chirag, Divya]

What this code does

  • hostel.remove(name) changes the list while the for-each loop's hidden iterator is walking it. On the next next(), the iterator sees that modCount changed and throws.
  • removeIf loops and removes in one safe step. No threads are involved here at all: CME is about changing a collection during a loop.

Example 4 · CME when another thread adds

CmeTwoThreadsDemo.javaJava
import java.util.ArrayList;import java.util.ConcurrentModificationException;import java.util.List;
public class CmeTwoThreadsDemo {    static volatile boolean writerDone = false;
    public static void main(String[] args) throws InterruptedException {        List<Integer> marks = new ArrayList<>();        for (int i = 0; i < 1_000; i++) {            marks.add(70);        }
        Thread reader = new Thread(() -> {            int passes = 0;            try {                while (!writerDone) {                    long total = 0;                    for (int m : marks) {          // iterating ...                        total += m;                    }                    passes++;                }                System.out.println("reader: no error this time, " + passes + " passes");            } catch (ConcurrentModificationException e) {                System.out.println("reader: stopped by ConcurrentModificationException");            }        }, "report-reader");
        Thread writer = new Thread(() -> {            for (int i = 0; i < 100_000; i++) {                marks.add(85);                    // ... while another thread adds            }            writerDone = true;        }, "marks-writer");
        reader.start();        writer.start();        reader.join();        writer.join();        System.out.println("writer: finished adding");    }}
Sample output
reader: stopped by ConcurrentModificationException
writer: finished adding

What this code does

  • The reader keeps looping over the marks while the writer adds 100,000 more. The iterator notices the change and stops with a CME on most runs.
  • This is luck, not protection. The fail-fast check is not synchronized, so on another run the reader could finish with a wrong total and no error.

Each ArrayList and HashMap keeps a change counter called modCount. The iterator remembers its value when the loop starts and checks it on every next(). If the number has changed, the iterator gives up at once instead of returning wrong data. Iterators that work like this are called fail-fast. The name sounds like a threading error, but the most common cause is one thread removing items inside its own for-each loop (Example 3). With two threads (Example 4) a CME is one possible symptom of unsafe sharing. Use removeIf or Iterator.remove() to remove items while looping.

Fail-fast checks are best effort only. The Java docs say a program must not depend on getting a CME: with threads, the loop may just as well read wrong or missing data with no exception.

Vector and Hashtable as legacy options

Vector and Hashtable are the Java 1.0 thread-safe versions of ArrayList and HashMap. Every public method is synchronized, so only one thread at a time can be inside any method of that object.

Example 5 · Vector and Hashtable keep every item

LegacySafeDemo.javaJava
import java.util.Hashtable;import java.util.List;import java.util.Map;import java.util.Vector;
public class LegacySafeDemo {    public static void main(String[] args) throws InterruptedException {        List<Integer> tickets = new Vector<>();            // every method is synchronized        Map<Integer, String> results = new Hashtable<>();  // same idea for a map
        Runnable work = () -> {            for (int i = 0; i < 100_000; i++) {                tickets.add(i);                results.put(i, "PASS");                     // both threads use the same keys            }        };
        Thread t1 = new Thread(work, "counter-1");        Thread t2 = new Thread(work, "counter-2");        t1.start();        t2.start();        t1.join();        t2.join();
        System.out.println("Vector size:    " + tickets.size());        System.out.println("Hashtable size: " + results.size());    }}
Output
Vector size:    200000
Hashtable size: 100000

What this code does

  • The same test as Example 1, but every add and put takes the object's lock, so the threads take turns and nothing is lost. The output is the same on every run.
  • The Hashtable has 100,000 entries, not 200,000, because both threads put the same keys and the second put replaces the first.

Example 5 runs the same two-thread test as before and always gets the right size.

They are called legacy classes (old classes kept so that old code still runs) because better tools exist now. New code should not pick them first.

  • One lock for the whole object: under many threads, everyone waits in one line.
  • Each method is safe on its own, but two calls in a row, such as if (!v.contains(x)) v.add(x), can still interleave.
  • Looping over a Vector while another thread changes it can still throw a CME.
  • Hashtable rejects null keys and values with a NullPointerException.
Often the simplest fix is to share nothing: each thread fills its own ArrayList, and main merges the lists after join(). The next lessons of this module cover the modern shared options.

Next step

Check your understanding

12 quick questions