java多线程--AtomicReference

AtomicReference介绍

AtomicReference是作用是对”对象”进行原子操作。

AtomicReference源码分析(基于JDK1.7.0_40)

在JDK1.7.0_40中AtomicReference.java的源码如下:

   
   
  1. public class AtomicReference<V>  implements java.io.Serializable {  
  2.     private static final long serialVersionUID = -1848883965231344442L;  
  3.   
  4.     // 获取Unsafe对象,Unsafe的作用是提供CAS操作  
  5.     private static final Unsafe unsafe = Unsafe.getUnsafe();  
  6.     private static final long valueOffset;  
  7.   
  8.     static {  
  9.       try {  
  10.         valueOffset = unsafe.objectFieldOffset  
  11.             (AtomicReference.class.getDeclaredField(“value”));  
  12.       } catch (Exception ex) { throw new Error(ex); }  
  13.     }  
  14.   
  15.     // volatile类型  
  16.     private volatile V value;  
  17.   
  18.     public AtomicReference(V initialValue) {  
  19.         value = initialValue;  
  20.     }  
  21.   
  22.     public AtomicReference() {  
  23.     }  
  24.   
  25.     public final V get() {  
  26.         return value;  
  27.     }  
  28.   
  29.     public final void set(V newValue) {  
  30.         value = newValue;  
  31.     }  
  32.   
  33.     public final void lazySet(V newValue) {  
  34.         unsafe.putOrderedObject(this, valueOffset, newValue);  
  35.     }  
  36.   
  37.     public final boolean compareAndSet(V expect, V update) {  
  38.         return unsafe.compareAndSwapObject(this, valueOffset, expect, update);  
  39.     }  
  40.   
  41.     public final boolean weakCompareAndSet(V expect, V update) {  
  42.         return unsafe.compareAndSwapObject(this, valueOffset, expect, update);  
  43.     }  
  44.   
  45.     public final V getAndSet(V newValue) {  
  46.         while (true) {  
  47.             V x = get();  
  48.             if (compareAndSet(x, newValue))  
  49.                 return x;  
  50.         }  
  51.     }  
  52.   
  53.     public String toString() {  
  54.         return String.valueOf(get());  
  55.     }  
  56. }<span style=”font-family: ‘Courier New’ !important; font-size: 12px !important; line-height: 1.5 !important; color: rgb(0, 0, 0);”></span>  
public class AtomicReference<V>  implements java.io.Serializable {
    private static final long serialVersionUID = -1848883965231344442L;

    // 获取Unsafe对象,Unsafe的作用是提供CAS操作
    private static final Unsafe unsafe = Unsafe.getUnsafe();
    private static final long valueOffset;

    static {
      try {
        valueOffset = unsafe.objectFieldOffset
            (AtomicReference.class.getDeclaredField("value"));
      } catch (Exception ex) { throw new Error(ex); }
    }

    // volatile类型
    private volatile V value;

    public AtomicReference(V initialValue) {
        value = initialValue;
    }

    public AtomicReference() {
    }

    public final V get() {
        return value;
    }

    public final void set(V newValue) {
        value = newValue;
    }

    public final void lazySet(V newValue) {
        unsafe.putOrderedObject(this, valueOffset, newValue);
    }

    public final boolean compareAndSet(V expect, V update) {
        return unsafe.compareAndSwapObject(this, valueOffset, expect, update);
    }

    public final boolean weakCompareAndSet(V expect, V update) {
        return unsafe.compareAndSwapObject(this, valueOffset, expect, update);
    }

    public final V getAndSet(V newValue) {
        while (true) {
            V x = get();
            if (compareAndSet(x, newValue))
                return x;
        }
    }

    public String toString() {
        return String.valueOf(get());
    }
}<span style="font-family: 'Courier New' !important; font-size: 12px !important; line-height: 1.5 !important; color: rgb(0, 0, 0);"></span>

说明
AtomicReference的源码比较简单。它是通过”volatile”和”Unsafe提供的CAS函数实现”原子操作。
(01) value是volatile类型。这保证了:当某线程修改value的值时,其他线程看到的value值都是最新的value值,即修改之后的volatile的值。
(02) 通过CAS设置value。这保证了:当某线程池通过CAS函数(如compareAndSet函数)设置value时,它的操作是原子的,即线程在操作value时不会被中断。

 

AtomicReference示例

   
   
  1. // AtomicReferenceTest.java的源码  
  2. import java.util.concurrent.atomic.AtomicReference;  
  3.   
  4. public class AtomicReferenceTest {  
  5.       
  6.     public static void main(String[] args){  
  7.   
  8.         // 创建两个Person对象,它们的id分别是101和102。  
  9.         Person p1 = new Person(101);  
  10.         Person p2 = new Person(102);  
  11.         // 新建AtomicReference对象,初始化它的值为p1对象  
  12.         AtomicReference ar = new AtomicReference(p1);  
  13.         // 通过CAS设置ar。如果ar的值为p1的话,则将其设置为p2。  
  14.         ar.compareAndSet(p1, p2);  
  15.   
  16.         Person p3 = (Person)ar.get();  
  17.         System.out.println(”p3 is ”+p3);  
  18.         System.out.println(”p3.equals(p1)=”+p3.equals(p1));  
  19.     }  
  20. }  
  21.   
  22. class Person {  
  23.     volatile long id;  
  24.     public Person(long id) {  
  25.         this.id = id;  
  26.     }  
  27.     public String toString() {  
  28.         return “id:”+id;  
  29.     }  
  30. }<span style=”font-family: ‘Courier New’ !important; font-size: 12px !important; line-height: 1.5 !important; color: rgb(0, 0, 0);”></span>  
// AtomicReferenceTest.java的源码
import java.util.concurrent.atomic.AtomicReference;

public class AtomicReferenceTest {

    public static void main(String[] args){

        // 创建两个Person对象,它们的id分别是101和102。
        Person p1 = new Person(101);
        Person p2 = new Person(102);
        // 新建AtomicReference对象,初始化它的值为p1对象
        AtomicReference ar = new AtomicReference(p1);
        // 通过CAS设置ar。如果ar的值为p1的话,则将其设置为p2。
        ar.compareAndSet(p1, p2);

        Person p3 = (Person)ar.get();
        System.out.println("p3 is "+p3);
        System.out.println("p3.equals(p1)="+p3.equals(p1));
    }
}

class Person {
    volatile long id;
    public Person(long id) {
        this.id = id;
    }
    public String toString() {
        return "id:"+id;
    }
}<span style="font-family: 'Courier New' !important; font-size: 12px !important; line-height: 1.5 !important; color: rgb(0, 0, 0);"></span>

运行结果

   
   
  1. p3 is id:102  
  2. p3.equals(p1)=false<span style=“font-family: ‘Courier New’ !important; font-size: 12px !important; line-height: 1.5 !important; color: rgb(0, 0, 255);”></span>  
p3 is id:102
p3.equals(p1)=false<span style="font-family: 'Courier New' !important; font-size: 12px !important; line-height: 1.5 !important; color: rgb(0, 0, 255);"></span>

结果说明
新建AtomicReference对象ar时,将它初始化为p1。
紧接着,通过CAS函数对它进行设置。如果ar的值为p1的话,则将其设置为p2。
最后,获取ar对应的对象,并打印结果。p3.equals(p1)的结果为false,这是因为Person并没有覆盖equals()方法,而是采用继承自Object.java的equals()方法;而Object.java中的equals()实际上是调用”==”去比较两个对象,即比较两个对象的地址是否相等。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值