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();
}
}
- using atomic methods with a thread-safe data structure may still lead to wrong results
- synchronized sometimes still necessary for typical operations on a list (check and modify)
/** 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();
}
}
- make that atomic which should be atomic