Thursday 10 December 2015

What is the problem if I synchronized only setters to make an object Thread-safe?

Scenario

Make setters synchronized only

public class ThreadSafeObject {
    private int value;

    public int getValue() {
        return value;
    }
    public synchronized void setValue(int value) {
        this.value = value;
    }
}

Changes to the object may not be visible to any reading thread, because JVM will not ensure that the reading thread's memory (like, cache) is in sync with the writing thread.

So, reader thread may still get out-of-date (older) values from its thread's cache than new value set by writing thread.

Solution

1.Make getters and setters both synchronized: No dirty read

When getters are synchronized, there will be lock on the object which will not allow other threads to modify the object state.
And synchronized also help to read the object from Main memory (not from cache) i.e NO DIRTY READ.

2.Use volatile keyword to ensure that the value has been read from Main memory.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...