Chapter 2: Protect Your Shared Mutable Collection Use Synchronized Collections →

Protect Your Collections

/** not thread-safe */
class Crew {

  private final List<String> members = new ArrayList<>();

  void add(String name) {
    if (!members.contains(name)) {
      members.add(name);
    }
  }

  int size(){
    return this.members.size();
  }
}

The Crew keeps a list of unique member names. It's documented as not thread-safe, and for good reason: an ArrayList must not be modified by several threads at the same time, it can end up in a corrupt state.

Declaring the field final doesn't help here: it only prevents assigning another list, the list itself can still change. And add() has a subtle problem of its own. It first checks whether the name is in the list and then adds it. Two threads adding the same name can both pass the check before either adds, and the name ends up in the list twice.

/** thread-safe */
class Crew {

  /** guarded by 'members' */
  private final List<String> members = new ArrayList<>();

  void add(String name) {
    synchronized (this.members) {
      if (!this.members.contains(name)) {
        this.members.add(name);
      }
    }
  }

  int size() {
    synchronized (this.members) {
      return this.members.size();
    }
  }
}

Both methods now synchronize on the list, and the documentation says so. Inside add(), the check and the insertion form one critical section, so no other thread can add the same name in between. size() synchronizes as well, so it never reads the list in the middle of a change and always sees the latest state.

This is the standard way to protect any shared state: one lock, documented, held for every access. As in the previous chapter, the lock is a private final field that no outside code can reach.