Does the actual value of the lock matter when deciding whether to use volatility?

Let's 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 that the following versions of the add method should have number as mutable in the following 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 atomic operations, but my question is that the value of number guarennteed is displayed in the global memory and is visible to all threads without using variability?

+7
source share
2 answers

- the value of the number, which should be pushed into the global memory and visible to all threads without using volatile?

Yes. synchronization also provides visibility. In fact, synchronization provides visibility and atomicity, and volatility only visibility.

+10
source

You did not synchronize so that your code is not thread safe:

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

In addition, synchronization guarantees visibility, as already noted by Eugene.

+1
source

All Articles