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.
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
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:
-
First is atomicity of the operation
-
Second is the memory visibility of the changes made by one thread to all other threads (Brian Goetz article on read and write barriers).
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:
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.
public synchronized E get(int index) {
if (index >= elementCount)
throw new ArrayIndexOutOfBoundsException(index);
return elementData(index);
}
Happy coding.
Top articles in this category:
- Can two threads call two different synchronized instance methods of an Object?
- What is purpose of Collections.unmodifiableCollection
- What are four principles of OOP, How aggregation is different than Composition?
- What is Double Checked Locking Problem in Multi-Threading?
- Producer Consumer Problem using Blocking Queue in Java
- What is Immutable Class in Java
- ThreadLocal with examples in Java