volatile, atomic, synchronized(二)

AtomicReference

The additional power provided by AtomicReference is the compareAndSet() method and friends.

If you do not need those methods, a volatile reference provides the same semantics as AtomicReference.set() and .get().

AtomicReference vs. Volatile

目前来看,atomic比volatile多了个原子性。

当多线程一起访问的时候,也可以达到原子切换生效,并对各线程都可见。

不过,对于普通的”=”来说,不是也可以做到原子切换么?(除了long, double),为什么还一定要用atomicReference?

AtomicReference vs. Synchronized

atomicReference只是锁定(只是像锁定,但没有真正的锁)某个变量,进行原子切换,并使值对各线程都生效。

synchronized可以真正锁定对象,做很多事情,如果这些事情中包括了对变量的修改,那么这些变量的修改,对其他线程也是可见的。

demo验证:

to be continued…

something interesting:

Consider:

AtomicReference ref = new AtomicReference(foo);

Thread A: Object oldVal = ref.getAndSet(bar);

Thread B: Object oldVal = ref.getAndSet(woz);

If thread A and B are executing concurrently, we are not guaranteed which one will execute first (your argument). We are, however, guaranteed that A and B will each have different values for oldVal, namely one will be foo and depending on who wins the race, bar or woz. We are guaranteed here that Thread A.oldVal != Thread B.oldVal.

Compare this to the volatile version:

Object ref = foo;

Thread A: Object oldVal = ref; ref = bar;

Thread B: Object oldVal = ref; ref = woz;

Here, both threads could wind up with oldVal being foo (Thread A.oldVal != ThreadB.oldVal no longer holds). We still don't have a guarantee about who will win the race, so ref could end up being bar or woz, as in our AtomicReference example.

The point is about atomicity of the get and set operation which otherwise is two operations.

原文地址:https://www.cnblogs.com/alipayhutu/p/2706335.html