Use Concurrent Collections
/** thread-safe */
class Crew {
private final List<String> members = Collections.synchronizedList(new ArrayList<>());
void add(String name) {
synchronized (this.members) {
if (!members.contains(name)) {
this.members.add(name);
}
}
}
int size() {
return this.members.size();
}
}
Even with a synchronized collection, the check-then-add sequence still needs an explicit synchronized block. Thread-safe methods don't make a sequence of calls thread-safe, and that's easy to miss.
/** thread-safe */
class Crew {
private final CopyOnWriteArrayList<String> members = new CopyOnWriteArrayList<>();
void add(String name) {
this.members.addIfAbsent(name);
}
int size() {
return this.members.size();
}
}
A CopyOnWriteArrayList offers exactly the operation we need: addIfAbsent() checks and adds atomically in one call. Make atomic what should be atomic, and the explicit lock disappears completely.
The name tells you the trade-off: every modification copies the whole underlying array, while reads need no locking at all. That makes it a great fit for small lists that are read often and changed rarely, like the members of a crew. For large or frequently changing collections, look at other classes in java.util.concurrent, such as ConcurrentHashMap, whose key set offers the same set semantics.