J.U.C并发框架源码阅读(一)AtomicInteger
基于版本jdk1.7.0_80
java.util.concurrent.atomic.AtomicInteger
代码如下
/*
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/ /*
*
*
*
*
*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/publicdomain/zero/1.0/
*/ package java.util.concurrent.atomic;
import sun.misc.Unsafe; /**
* An {@code int} value that may be updated atomically. See the
* {@link java.util.concurrent.atomic} package specification for
* description of the properties of atomic variables. An
* {@code AtomicInteger} is used in applications such as atomically
* incremented counters, and cannot be used as a replacement for an
* {@link java.lang.Integer}. However, this class does extend
* {@code Number} to allow uniform access by tools and utilities that
* deal with numerically-based classes.
*
* @since 1.5
* @author Doug Lea
*/
public class AtomicInteger extends Number implements java.io.Serializable {
private static final long serialVersionUID = 6214790243416807050L; // setup to use Unsafe.compareAndSwapInt for updates
private static final Unsafe unsafe = Unsafe.getUnsafe();
private static final long valueOffset; static {
try {
valueOffset = unsafe.objectFieldOffset
(AtomicInteger.class.getDeclaredField("value"));
} catch (Exception ex) { throw new Error(ex); }
} private volatile int value; /**
* Creates a new AtomicInteger with the given initial value.
*
* @param initialValue the initial value
*/
public AtomicInteger(int initialValue) {
value = initialValue;
} /**
* Creates a new AtomicInteger with initial value {@code 0}.
*/
public AtomicInteger() {
} /**
* Gets the current value.
*
* @return the current value
*/
public final int get() {
return value;
} /**
* Sets to the given value.
*
* @param newValue the new value
*/
public final void set(int newValue) {
value = newValue;
} /**
* Eventually sets to the given value.
*
* @param newValue the new value
* @since 1.6
*/
public final void lazySet(int newValue) {
unsafe.putOrderedInt(this, valueOffset, newValue);
} /**
* Atomically sets to the given value and returns the old value.
*
* @param newValue the new value
* @return the previous value
*/
public final int getAndSet(int newValue) {
for (;;) {
int current = get();
if (compareAndSet(current, newValue))
return current;
}
} /**
* Atomically sets the value to the given updated value
* if the current value {@code ==} the expected value.
*
* @param expect the expected value
* @param update the new value
* @return true if successful. False return indicates that
* the actual value was not equal to the expected value.
*/
public final boolean compareAndSet(int expect, int update) {
return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
} /**
* Atomically sets the value to the given updated value
* if the current value {@code ==} the expected value.
*
* <p>May <a href="package-summary.html#Spurious">fail spuriously</a>
* and does not provide ordering guarantees, so is only rarely an
* appropriate alternative to {@code compareAndSet}.
*
* @param expect the expected value
* @param update the new value
* @return true if successful.
*/
public final boolean weakCompareAndSet(int expect, int update) {
return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
} /**
* Atomically increments by one the current value.
*
* @return the previous value
*/
public final int getAndIncrement() {
for (;;) {
int current = get();
int next = current + 1;
if (compareAndSet(current, next))
return current;
}
} /**
* Atomically decrements by one the current value.
*
* @return the previous value
*/
public final int getAndDecrement() {
for (;;) {
int current = get();
int next = current - 1;
if (compareAndSet(current, next))
return current;
}
} /**
* Atomically adds the given value to the current value.
*
* @param delta the value to add
* @return the previous value
*/
public final int getAndAdd(int delta) {
for (;;) {
int current = get();
int next = current + delta;
if (compareAndSet(current, next))
return current;
}
} /**
* Atomically increments by one the current value.
*
* @return the updated value
*/
public final int incrementAndGet() {
for (;;) {
int current = get();
int next = current + 1;
if (compareAndSet(current, next))
return next;
}
} /**
* Atomically decrements by one the current value.
*
* @return the updated value
*/
public final int decrementAndGet() {
for (;;) {
int current = get();
int next = current - 1;
if (compareAndSet(current, next))
return next;
}
} /**
* Atomically adds the given value to the current value.
*
* @param delta the value to add
* @return the updated value
*/
public final int addAndGet(int delta) {
for (;;) {
int current = get();
int next = current + delta;
if (compareAndSet(current, next))
return next;
}
} /**
* Returns the String representation of the current value.
* @return the String representation of the current value.
*/
public String toString() {
return Integer.toString(get());
} public int intValue() {
return get();
} public long longValue() {
return (long)get();
} public float floatValue() {
return (float)get();
} public double doubleValue() {
return (double)get();
} }
1. CAS
CAS Compare And Swap,顾名思义,比较并交换
一般的形式是cas(pointer, expect, update),其含义为:比较pointer指向的值与expect,如果两者相等,则将pointer指向的值更新为update并返回ture,如果两者不等,返回false
如果有多个线程同时对同一个pointer调用cas函数,那么只有一个线程能成功pointer指向的值并返回true,其他线程都会返回false
也就是说这是一个原子操作,它需要cpu层面的支持,比方说cmpxchg函数
JDK内部实现了CAS操作,但是不对外开放(用反射强行拿当然可以)
2. sun.misc.Unsafe
这里我们主要用的是Unsafe提供的CAS功能,提供了如下的代码
public final native boolean compareAndSwapObject(Object var1, long var2, Object var4, Object var5);
public final native boolean compareAndSwapInt(Object var1, long var2, int var4, int var5);
public final native boolean compareAndSwapLong(Object var1, long var2, long var4, long var6);
native的,估计底层的jni代码会根据运行平台调用对应的汇编码,比方说如果是intel 的x86架构,就cmpxchg走一走
3. 实现原理
AtomicInteger内部维护了一个volatile类型的int变量value
value用volatile修饰是为了利用volatile带来的内存可见性语义。
想象一个场景,有两个线程A和B,线程B先修改了value,线程A再去读value。
如果没有volatile修饰,可能B读到的是线程A修改之前的值。但是加上volatile之后,线程A对value的修改一定对B可见,所以B可以读到最新的值。(实现原理是线程A在写入value之后,插入一条storeload内存屏障,对于Intel的x86架构,就是插入一条带lock前缀的空转指令(lock addl $0x0,(%esp)),这个操作会导致线程A所在的core的cache line(其中肯定包含了value)回写到主存,以及使其他core中对应的cache line(其中肯定包含了value)被设为invalid,那么线程B所在的其他core想要读取value的时候,由于cache line被invalid,就只能从主存中取值,这时拿到的值就是线程A更新后最新的值了)
但是volatile的内存可见性语义还不够,同样设想一个场景,两个线程A和B在不同的core上工作,并发对value=0进行自增操作。两个core并发的将value加载到cache line,然后同时将value加载到寄存器中。线程A先对寄存器中的value自增(缓存一致性协议管不到寄存器),得到value=1,然后将其写入cache line,缓存一致性协议工作,将线程B所在的core的对应的cache line设置为invalid。这时线程B再执行,也将寄存器中的value自增,得到value=1,想要写入到cache line,但是对应的cache line已经是invalid了,于是从主存中取最新的value=1加载到cache line中来,然后写入,触发缓存一致性协议,将value=1写回到主存中。最终还是得到value=1的结果。
为了避免这种情况,最简单的想法就是加锁,将value作为临界区,多个线程不能同时操作,但是加锁是一个比较重的操作,比较浪费。
AtomicInteger的做法是volatile配合CAS使用,如果有线程想更新value,那么记下value的当前值expect,以及需要更新到的新值update=expect+1
然后调用cas指令:cas(value, expect, update)
在无竞争的情况下,cas直接更新成功
在有竞争的情况下,可能在执行cas之前,value被其他线程修改成了新值,那么由于cas条件中的expect与value的当前值不等,会导致cas操作失败并返回false,我们检测到cas操作失败,直接重试即可,总有一次能成功的。
4. 实现代码
public final int incrementAndGet() {
for (;;) {//无限循环
int current = get();//获取value当前值
int next = current + 1;//算出value的期望值
if (compareAndSet(current, next))//尝试cas更新value
return next;//成功,函数返回
}//失败,继续cas,总有一次能更新成功的
}
挑increaseAndGet这一个方法就行了,很有代表性
public final boolean compareAndSet(int expect, int update) {
return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}
compareAndSet的实现则是直接调用Unsafe的代码了,native的不好跟
java.util.concurrent.atomic包里还有其他的一堆class,AtomicLong,AtomReference等,原理都差不多,在此就不赘述了
参考文献
J.U.C并发框架源码阅读(一)AtomicInteger的更多相关文章
- J.U.C并发框架源码阅读(二)AbstractQueuedSynchronizer
基于版本jdk1.7.0_80 java.util.concurrent.locks.AbstractQueuedSynchronizer 代码如下 /* * ORACLE PROPRIETARY/C ...
- J.U.C并发框架源码阅读(六)ConditionObject
基于版本jdk1.7.0_80 java.util.concurrent.locks.AbstractQueuedSynchronizer.ConditionObject 代码如下 /** * Con ...
- J.U.C并发框架源码阅读(五)Semaphore
基于版本jdk1.7.0_80 java.util.concurrent.Semaphore 代码如下 /* * ORACLE PROPRIETARY/CONFIDENTIAL. Use is sub ...
- J.U.C并发框架源码阅读(八)ArrayBlockingQueue
基于版本jdk1.7.0_80 java.util.concurrent.ArrayBlockingQueue 代码如下 /* * ORACLE PROPRIETARY/CONFIDENTIAL. U ...
- J.U.C并发框架源码阅读(十三)ThreadPoolExecutor
基于版本jdk1.7.0_80 java.util.concurrent.ThreadPoolExecutor 代码如下 /* * ORACLE PROPRIETARY/CONFIDENTIAL. U ...
- J.U.C并发框架源码阅读(十五)CopyOnWriteArrayList
基于版本jdk1.7.0_80 java.util.concurrent.CopyOnWriteArrayList 代码如下 /* * Copyright (c) 2003, 2011, Oracle ...
- J.U.C并发框架源码阅读(三)ReentrantLock
基于版本jdk1.7.0_80 java.util.concurrent.locks.ReentrantLock 代码如下 /* * ORACLE PROPRIETARY/CONFIDENTIAL. ...
- J.U.C并发框架源码阅读(十二)ConcurrentHashMap
基于版本jdk1.7.0_80 java.util.concurrent.ConcurrentHashMap 代码如下 /* * ORACLE PROPRIETARY/CONFIDENTIAL. Us ...
- J.U.C并发框架源码阅读(七)CyclicBarrier
基于版本jdk1.7.0_80 java.util.concurrent.CyclicBarrier 代码如下 /* * ORACLE PROPRIETARY/CONFIDENTIAL. Use is ...
随机推荐
- sprintf()函数使用异常
调试STM32F103,比如如下代码:使用springf函数,这个函数是把最后两个参数先格式化成字符串 ,输出到ERROR_STRING,如果他们合并的长度大于30会出现深情况? ] sprintf( ...
- linux ubuntu 现在显示的是ubuntu login
linux ubuntu 现在显示的是ubuntu login 如果要进图形界面,你需要安装桌面管理器sudo apt-get install ubuntu-desktop或sudo apt-get ...
- 《Cracking the Coding Interview》——第7章:数学和概率论——题目2
2014-03-20 01:59 题目:有n只蚂蚁在正n边形的n个顶点,同时以同速率开始沿着边走.每只蚂蚁走的方向是随机的,那么这些蚂蚁至少有两只发生碰撞的概率是多少. 解法:只有所有蚂蚁都往一个方向 ...
- USACO Section2.3 Controlling Companies 解题报告 【icedream61】
concom解题报告------------------------------------------------------------------------------------------ ...
- 恢复误删除表黑科技之relay log大法
Preface In my previous blogs,I've demonstrated several mothods of how to rescue a dropped ta ...
- eclipse进阶功法
先选择要操作的行,在同时按shift+alt+a,会将所选中的文字括起来,鼠标会变成十字图标,按住鼠标左键,在相应输入文字的位置上下拖动,会出现一个竖杠,此时即可开始输入文字了,并且所选中行都有.
- 设计模式之模板方法模式 templateMethod
代码实现 public abstract class BankTemplateMethod { //具体方法 public void takeNumber(){ System.out.println( ...
- Codeforces 1088E 树形dp+思维
比赛的时候看到题意没多想就放弃了.结果最后D也没做出来,还掉分了,所以还是题目做的太少,人太菜. 回到正题: 题意:一棵树,点带权值,然后求k个子连通块,使得k个连通块内所有的点权值相加作为分子除以k ...
- leetcode_day02
任务二:删除排序数组中的重复项 原文链接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array/ 最开始的解决思路: ...
- win10下乌龟git安装和使用
一.安装git for windows 首先下载git for windows客户端http://msysgit.github.io/ 安装过程没什么特别的,不停next就ok了 图太多就不继 ...