javamultithreadingcopyonwritearraylist

Is a modifying operation thread safe on a List if the underlying datastracture is CopyOnWriteArrayList?


I want to make my modifying operations thread safe, while also adhering to best practices regarding the design of the application.

I have let's say a Zoo class that manages the animals within it, like adding a new Animal to the zoo, removing one and so on, and I want these operations to be thread safe. For simplicity I have a private List<Animal> animals variable in the zoo. My first thought was to initialize the animals variable as a CopyOnWriteArrayList object within the constructor, whenever a new Zoo object is created, like so:

private List<Animal> animals;

public Zoo() {
    this.animals = new CopyOnWriteArrayList<>();
}

public Zoo(List<Animal> animals) {
    this();
    addAnimals(animals);
}

public void addAnimals(Collection<Animal> animalsToAdd) {
    animals.addAll(animalsToAdd);
}

As far as I have understood, the methods of CopyOnWriteArrayList are thread safe, but can I achieve thread safety this way, i.e: by having the underlying datastructure be a CopyOnWriteArrayList, while keeping the reference variable as a List? Or making the List<Animal> animals variable volatile and the methods in question synchronized, would be a better option?


Solution

  • It is threadsafe as is. You'd only need to consider making animals volatile and/or adding your own synchronization if you were changing the this.animals reference with this.animals = .... If you simply set it once in the constructor and never change it again then you're already good to go.