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?
Yes. synchronization offers visibility also. Actually synchronization offers visibility and atomicity, while volatile only visibility.