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

Munish Chandel | April 07, 2019 at 09:55 PM | 17 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.



You may also be interested in..
Generic placeholder image
ebook PDF - Cracking Spring Microservices Interviews for Java Developers
You may also be interested in..
Generic placeholder image
ebook PDF - Cracking Java Interviews v3.4 by Munish Chandel

Similar Articles:
  1. Java 8 – HijrahDate, How to calculate the Ramadan date
  2. How to find if the Linked List contains any Cycle/Loop
  3. How will you calculate factorial of a large number in Java
  4. Generate Random Numbers in a range using Java 8
  5. What is difference between JDK JRE and JVM
  6. Difference between Comparable and Comparator in Java with Examples
  7. What will happen if we don't synchronize getters/accessors of a shared mutable object in multi-threaded applications

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