Shawn
Shawn

Reputation: 7365

Does the actual lock matter when deciding to use volatile?

Say I have the following code:

private Integer number;
private final Object numberLock = new Object();

public int get(){
    synchronized(number or numberLock){
        return Integer.valueOf(number);
     }
}

My question is, do the following versions of the add method need to have number as volatile in the below cases:

public void add(int num){
    synchronized(number)
        number = number + num;
}

public void add(int num){
    synchronized(numberLock)
        number = number + num;
}

I understand that these are both atomic operations, but my question is, is the value of number guarennteed to be pushed out to global memory and visible to all threads without using volatile?

Upvotes: 7

Views: 127

Answers (2)

Victor Parmar
Victor Parmar

Reputation: 5789

You haven't synchronized get so your code is not thread-safe:

public int get(){
    return Integer.valueOf(number);
}

Apart from that, synchronization will guarantee visibility as Eugene already noted.

Upvotes: 1

Eugene
Eugene

Reputation: 121088

is the value of number guarennteed to be pushed out to global memory and visible to all threads without using volatile?

Yes. synchronization offers visibility also. Actually synchronization offers visibility and atomicity, while volatile only visibility.

Upvotes: 10

Related Questions