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 ...
随机推荐
- cycling -avoid the vicious cycle
‘Numerous' studies in the past appear to have shown a link between cycling and ED. The researchers a ...
- Hyper-V中的Linux无法配置网络地址的解决办法
一周碰到2次在Hyper-V 2012中安装了Linux,也安装了IC 3.4.但是却无法配置IP地址的问题.因此造成很多不便,因此找机会把这个原因和解决办法进行了尝试. 这过程中感谢同事的提示,让我 ...
- 【转】灰色在PPT中的运用
一.作为背景 灰色作为背景能够有效烘托其他元素,特别是与白/黑色渐变,效果更好. 1.黑灰渐变,科技感十足 2.纯灰:简单清晰 http://www.behance.net/gallery/N ...
- 机器学习tensorflow框架初试
本文来自网易云社区 作者:汪洋 前言 新手学习可以点击参考Google的教程.开始前,我们先在本地安装好 TensorFlow机器学习框架. 首先我们在本地window下安装好python环境,约定安 ...
- 独立开发unity2d游戏的问答群
129443731 有志独立开发游戏的,只讨论最新的unity2d技术的.群里面主要已问答为主,喜欢聊天的就别加群了,灌水多了会被t.希望能对unity2d比较了解的已及喜欢学习的人加入.
- Asp.Net中Response.Cookies.Remove 无法删除COOKIE的问题解决方法
登陆功能经常需要使用Cookie来存储登陆信息,可是在开发过程中,经常发现cookie无法删除的问题.删除的代码无非就是找到Cookie并删除掉. 但是会发现 Response.Cookies.Rem ...
- 孤荷凌寒自学python第十四天python代码的书写规范与条件语句及判断条件式
孤荷凌寒自学python第十四天python代码的书写规范与条件语句及判断条件式 (完整学习过程屏幕记录视频地址在文末,手写笔记在文末) 在我学习过的所有语言中,对VB系的语言比较喜欢,而对C系和J系 ...
- 斐波那契数列的三种C++实现及时间复杂度分析
本文介绍了斐波那契数列的三种C++实现并详细地分析了时间复杂度. 斐波那契数列定义:F(1)=1, F(2)=1, F(n)=F(n-1) + F(n-2) (n>2) 如何计算斐波那契数 F( ...
- Leetcode 667.优美的排列II
优美的排列II 给定两个整数 n 和 k,你需要实现一个数组,这个数组包含从 1 到 n 的 n 个不同整数,同时满足以下条件: ① 如果这个数组是 [a1, a2, a3, ... , an] ,那 ...
- 爬虫:Scrapy11 - Logging
Scrapy 提供了 log 功能.可以通过 scrapy.log 模块使用.当前底层实现使用了 Twisted logging,不过可能在之后会有所变化. log 服务必须通过显式调用 scrapy ...