Do I need to synchronize items in a CopyOnWriteArrayList if they are updated and read by different threads?

StackOverflow https://stackoverflow.com/questions/22968968

Question

If I share a list of items between threads using a CopyOnWriteArrayList do I further need to synchronize the items if they are updated and read by different threads?

Currently my item class definition is below. Do I need to add synchronized to each getter and setter?

Basically I want to make sure changes by one thread are visible in another thread - i think the CopyOnWriteArrayList will provide a memory barrier to ensure this but i want to be sure - thanks

public class MyClass {
    private String string;
    private Long longObj;
    private long longprim;

    public String getString() {
        return string;
    }

    public void setString(String string) {
        this.string = string;
    }

    public Long getLongObj() {
        return longObj;
    }

    public void setLongObj(Long longObj) {
        this.longObj = longObj;
    }

    public long getLongprim() {
        return longprim;
    }

    public void setLongprim(long longprim) {
        this.longprim = longprim;
    }
}
Was it helpful?

Solution

Since your CopyOnWriteArrayList contains mutable items you need full synchronization for item class. Imagine, two threads access the same item within the list (safe list operations) and then manipulate this item (unsafe).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top