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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With