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

Carvia Tech | 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() {

    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 Immutable Class in Java
  3. Can the keys in HashMap be mutable
  4. ThreadLocal with examples in Java
  5. Producer Consumer Problem using Blocking Queue in Java
  6. What is difference between sleep() and wait() method in Java?
  7. Explain the threading Jargon in Java

Find more on this topic:
Core Java image
Core Java

Core Java - OOP Concepts, Garbage Collection, Multi-threading, Collections Framework, Java 8 Features, Lambda Functions, Streams.

Last updated 1 week ago

Recommended books for interview preparation:

This website uses cookies to ensure you get the best experience on our website. more info