首页 > 其他 > 详细

原子操作

时间:2016-01-31 13:17:53      阅读:160      评论:0      收藏:0      [点我收藏+]

大家都知道,读和写是两个操作,在多线程的时候通常需要加锁来保证其原子性,但是java自带的那一堆AutomicXX却不是这样做的

它们用的都是sun.misc.Unsafe里的方法,就是这几个compareAndSwapInt,compareAndSwapLong,和compareAndSwapObject

接受的4个参数,前两个是你要执行读写操作的对象和字段的偏移量,这两个共同确定一个读写操作的地址。如果实际的值和expect一样,就修改为update。

偏移量是字段相对于对象头位置来说的。使用compareAndSwapInt这个方法获得。

 

 

compareAndSwapInt

public boolean compareAndSwapInt(java.lang.Object obj,
                                 long offset,
                                 int expect,
                                 int update)
Compares the value of the integer field at the specified offset in the supplied object with the given expected value, and updates it if they match. The operation of this method should be atomic, thus providing an uninterruptible way of updating an integer field.

 


compareAndSwapLong

public boolean compareAndSwapLong(java.lang.Object obj,
                                  long offset,
                                  long expect,
                                  long update)
Compares the value of the long field at the specified offset in the supplied object with the given expected value, and updates it if they match. The operation of this method should be atomic, thus providing an uninterruptible way of updating a long field.

 


compareAndSwapObject

public boolean compareAndSwapObject(java.lang.Object obj,
                                    long offset,
                                    java.lang.Object expect,
                                    java.lang.Object update)
Compares the value of the object field at the specified offset in the supplied object with the given expected value, and updates it if they match. The operation of this method should be atomic, thus providing an uninterruptible way of updating an object field.

 

 

原子操作

原文:http://www.cnblogs.com/easyroom/p/5172857.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!