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 | 69 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. Can the keys in HashMap be mutable
  3. What is Immutable Class. Why would you choose it? How would you make a class immutable?
  4. What is ThreadLocal in Java, where will you use this class
  5. Producer Consumer Problem using Blocking Queue in Java
  6. What is difference between sleep() and wait() method in Java?
  7. What is Deadlock in Java? How to troubleshoot and how to avoid deadlock



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 month ago


Recommended books for interview preparation:

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