What will happen if we don't synchronize getters/accessors of a shared mutable object in multi-threaded applications

Upasana | April 22, 2019 | 1 min read | 438 views | Multithreading and Concurrency


From Effective Java 2nd Edition - Item 66

When multiple threads share mutable data, each thread that reads or writes the data must perform synchronization. In fact, synchronization has no effect unless both read and write operations are synchronized.

Synchronization serves two major purposes in a multi-threaded scenario:

  1. First is atomicity of the operation

  2. Second is the memory visibility of the changes made by one thread to all other threads (Brian Goetz article on read and write barriers).

In case of getters the changes made to the shared variable will get reflected to the new thread if the code block is synchronized, otherwise dirty reads may happen and the thread may see the stale state of the shared object.

So all the methods returning the mutable protected state of the shared object must be synchronized unless the field returned is immutable, final or volatile.

Let’s take example of a simple thread-safe Counter class:

thread-safe Counter
public class Counter {
    private int c = 0;

    public synchronized void increment() {
        c++;
    }

    public synchronized int getValue() {    (1)
        return c;
    }
}
1 Getters must be synchronized to see the guaranteed correct value in multi-threaded environment.

That’s the reason that get() method of Vector class is also synchronized, as shown in the below code snippet.

java.util.Vector from SDK
public synchronized E get(int index) {
    if (index >= elementCount)
        throw new ArrayIndexOutOfBoundsException(index);

    return elementData(index);
}

Happy coding.


Top articles in this category:
  1. Can two threads call two different synchronized instance methods of an Object?
  2. What is purpose of Collections.unmodifiableCollection
  3. What are four principles of OOP, How aggregation is different than Composition?
  4. What is Double Checked Locking Problem in Multi-Threading?
  5. Producer Consumer Problem using Blocking Queue in Java
  6. What is Immutable Class in Java
  7. ThreadLocal with examples in Java

Recommended books for interview preparation:

Find more on this topic:
Buy interview books

Java & Microservices interview refresher for experienced developers.