来源:AtomicReference与volatile的区别
AtomicReference与volatile的在可见性上的意义是一致的。
volatile不能保证原子性,AutomicReference实现上则用了volatile和Unsafe.compareAndSwapObject()来分别保证可见性和原子性。
1 package org.liws; 2 3 import java.util.concurrent.atomic.AtomicReference; 4 import org.junit.Test; 5 6 public class Snippet { 7 8 private static volatile Integer volatileInt = 0; 9 private static AtomicReference<Integer> atmicRef = new AtomicReference<Integer>(volatileInt); 10 11 /** 验证volatile不能保证原子性 */ 12 @Test public void test_volatile() throws InterruptedException { 13 for (int i = 0; i < 100; i++) { 14 new Thread(new Runnable() { 15 @Override public void run() { 16 for (int i = 0; i < 10000; i++) { 17 volatileInt++; 18 } 19 } 20 }).start(); 21 } 22 Thread.sleep(1000); 23 System.out.println(volatileInt); // something like 398793 24 } 25 26 /** 验证test_AtomicReference能保证原子性 */ 27 @Test public void test_AtomicReference() throws InterruptedException{ 28 for (int i = 0; i < 100; i++) { 29 new Thread(new Runnable(){ 30 @Override public void run() { 31 for (int i = 0; i < 10000; i++) { 32 while (true) { 33 Integer temp = atmicRef.get(); 34 if (atmicRef.compareAndSet(temp, temp + 1)) { 35 break; 36 } 37 } 38 } 39 } 40 }).start(); 41 } 42 Thread.sleep(1000); 43 System.out.println(atmicRef.get()); //1000000 44 } 45 }