Friday, 22 April 2016

What may be the scenario to make an object Thread-safe ?


Scenario 1. No use of synchronized keyword
The below class is not thread-safe, as we are not using synchronized keyword with getters / setters.
public class MyValue {
    private int value;

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

If multiple threads shares same instance of MyValue class and one thread calls setValue(123), without synchronized it is possible that other threads still keep getting old value.
 

Scenario 2. 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.


Scenario 3. Using synchronized with getters and setters both
public class MyValue {
    private int value;

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

Before leaving synchronized block, every write made is guaranteed to be in sync with every read made after entering a block synchronizing on the same object.


Scenario 4. Using volatile keyword
public class MyValue {
    private volatile int value;

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

Same behavior as Scenario 3.

No comments:

Post a Comment

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