Chapter 2: Protect Your Shared Mutable Collection ← Protect Your Collections Use Concurrent Collections →

Use Synchronized Collections

/** 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();
    }
  }
}

Every method that touches the list has to remember to synchronize. With two methods, that's manageable, but each new method is another chance to forget the lock, and forgetting it doesn't cause a compile error, just rare and hard-to-reproduce bugs.

/** thread-safe */
class Crew {

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

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

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

Collections.synchronizedList() wraps the list so that every single method call is synchronized on the wrapper. So size() no longer needs its own synchronized block.

But add() still does. Each call to contains() and add() is thread-safe on its own, but another thread can still run between the two. The check and the insertion have to happen atomically, so they still need a block that synchronizes on the list. Since the wrapper uses itself as its lock, synchronizing on members works together with the wrapper's own locking.