by BehindJava

In Java, do I need to declare my collection synchronized if it's read-only

Home » java » In Java, do I need to declare my collection synchronized if it's read-only

In this tutorial we are going to learn about declaring collection synchronized if it’s read-only.

Remember that by keeping a read-only collection you are only preventing modifications to the collection itself. Each collection element is still changeable.

class Test {
    public Test(final int a, final int b) {
        this.a = a;
        this.b = b;
    }

    public int a;
    public int b;
}

public class Main {

    public static void main(String[] args) throws Exception {
        List<Test> values = new ArrayList<Test>(2);
        values.add(new Test(1, 2));
        values.add(new Test(3, 4));

        List<Test> readOnly = Collections.unmodifiableList(values);
        for (Test t : readOnly) {
            t.a = 5;
        }

        for (Test t : values) {
            System.out.println(t.a);
        }
    }

}

Output:

5
5

Important considerations

  • It depends on if the threads that are reading your collection are started before or after you’re filling it. If they’re started before you fill it, you have no guarantees (without synchronizing), that these threads will ever see the updated values.
  • The reason for this is the Java Memory Model.
  • And even if the threads are started after you fill your collection, you might have to synchronize because your collection implementation could change its internal state even on read operations.