Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 570
Shawn Avatar asked Feb 06 '12 15:02

Shawn


2 Answers

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.

like image 88
Eugene Avatar answered Nov 09 '22 18:11

Eugene


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.

like image 26
Victor Parmar Avatar answered Nov 09 '22 19:11

Victor Parmar