Saturday, 23 April 2016

What is the problem if I override only getters to make an object Thread-safe ?


Scenario. Using synchronized with setters only
public class MyValue {
    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
Make getters and setters both synchronized.
OR
Use volatile keyword with the value and no need of using synchnozed

No comments:

Post a Comment

Note: only a member of this blog may post a comment.