/** 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();
}
}
}
- now thread-safe
- synchronized critical section with private lock object (link to other comparisons)
- the 'standard' way of protecting any shared state
- be aware: critical section encompasses both read and write, as it's atomic