代码改变世界

原子操作

2016-01-31 09:33  微服务专家  阅读(465)  评论(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.