Java 原子类 java.util.concurrent.atomic
Java 原子类 java.util.concurrent.atomic
1、i++为什么是非线程安全的
i++其实是分为3个步骤:获取i的值, 把i+1, 把i+1的结果赋给i
如果多线程执行i++操作,没有同步的话,结果可能不正确
如两个线程同时获取i的值,然后各自+1后,赋给i。正确的情况下i的值应该是加了2,但这里其实加了1而且,前面的结果被覆盖了。
通常做法:synchronized (synchronized方法,synchronized变量), 但这样做效率不是最优的。
2、AtomicInteger的实现
主要依靠:1、volatile 保证了变量的可见性,所有线程不缓存volatile变量,需要时都从内存读取,这样能保证所有数据拿到的值都是最新的。
2、compareAndSet(int expect, int update)判断当前值==expect?当前值=update:错误;
这里做了两步操作,判断跟赋值。但因为cpu提供这样指令的支持,所有能保证这个操作时原子的。
- public class AtomicIntegerextends Number
implements java.io.Serializable { - private staticfinal
long serialVersionUID = 6214790243416807050L; - // setup to use Unsafe.compareAndSwapInt for updates
- private staticfinal Unsafe unsafe = Unsafe.getUnsafe();
- private staticfinal
long valueOffset; - static {
- try {
- valueOffset = unsafe.objectFieldOffset
- (AtomicInteger.class.getDeclaredField("value"));
- } catch (Exception ex) {
throw new Error(ex); } - }
- private volatileint value;
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;
3、AtomicInteger 中的set(int newValue) lazySet(int newValue)
void set(int newValue)
设置为给定值。 直接修改原始值,也就是i=newValue操作。
void lazySet(int newValue) 最后设置为给定值。
延时设置变量值,这个等价于set()方法,但是由于字段是volatile类型的,因此次字段的修改会比普通字段(非volatile字段)有稍微的性能延时(尽管可以忽略),所以如果不是想立即读取设置的新值,允许在“后台”修改值,那么此方法就很有用。如果还是难以理解,这里就类似于启动一个后台线程如执行修改新值的任务,原线程就不等待修改结果立即返回(这种解释其实是不正确的,但是可以这么理解)。
4、AtomicInteger中compareAndSet(int expect, int update) weakCompareAndSet(int expect, int update)
boolean weakCompareAndSet(int expect, int update)
如果当前值 == 预期值,则以原子方式将该设置为给定的更新值。JSR规范中说:以原子方式读取和有条件地写入变量但不
创建任何 happen-before 排序,因此不提供与除weakCompareAndSet 目标外任何变量以前或后续读取或写入操作有关的任何保证。大意就是说调用weakCompareAndSet时并不能保证不存在happen-before的发生(也就是可能存在指令重排序导致此操作失败)。但是从Java源码来看,其实此方法并没有实现JSR规范的要求,最后效果和compareAndSet是等效的,都调用了unsafe.compareAndSwapInt()完成操作。
- /**
- * 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 finalboolean 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 finalboolean weakCompareAndSet(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.
*
* @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);
}
Java 原子类 java.util.concurrent.atomic的更多相关文章
- 原子类java.util.concurrent.atomic.*原理分析
原子类java.util.concurrent.atomic.*原理分析 在并发编程下,原子操作类的应用可以说是无处不在的.为解决线程安全的读写提供了很大的便利. 原子类保证原子的两个关键的点就是:可 ...
- Java并发—原子类,java.util.concurrent.atomic包(转载)
原子类 Java从JDK 1.5开始提供了java.util.concurrent.atomic包(以下简称Atomic包),这个包中 的原子操作类提供了一种用法简单.性能高效.线程安全地更新一个变量 ...
- java.util.concurrent.atomic 类包详解
java.util.concurrent包分成了三个部分,分别是java.util.concurrent.java.util.concurrent.atomic和java.util.concurren ...
- 并发之java.util.concurrent.atomic原子操作类包
15.JDK1.8的Java.util.concurrent.atomic包小结 14.Java中Atomic包的原理和分析 13.java.util.concurrent.atomic原子操作类包 ...
- Java多线程:CAS与java.util.concurrent.atomic
锁的几种概念 悲观锁 总是假设最坏的情况,每次获取数据都认为别人会修改,所以拿数据时会上锁,一直到释放锁不允许其他线程修改数据.Java中如synchronized和reentrantLock就是这种 ...
- java并发编程:线程安全管理类--原子包--java.util.concurrent.atomic
java.util.concurrent.atomic 的描述 AtomicBoolean 可以用原子方式更新的 boolean 值. AtomicInteger 可以用原子方式更新的 int 值. ...
- java.util.concurrent.atomic 包详解
Atomic包的作用: 方便程序员在多线程环境下,无锁的进行原子操作 Atomic包核心: Atomic包里的类基本都是使用Unsafe实现的包装类,核心操作是CAS原子操作 关于CAS compar ...
- 谈论高并发(十二)分析java.util.concurrent.atomic.AtomicStampedReference看看如何解决源代码CAS的ABA问题
于谈论高并发(十一)几个自旋锁的实现(五岁以下儿童)中使用了java.util.concurrent.atomic.AtomicStampedReference原子变量指向工作队列的队尾,为何使用At ...
- Java:多线程,java.util.concurrent.atomic包之AtomicInteger/AtomicLong用法
1. 背景 java.util.concurrent.atomic这个包是非常实用,解决了我们以前自己写一个同步方法来实现类似于自增长字段的问题. 在Java语言中,增量操作符(++)不是原子的,也就 ...
随机推荐
- linux设置网络三种方法
http://blog.csdn.net/u010003835/article/details/52233296
- 吴裕雄--天生自然ShellX学习笔记:Shell 变量
定义变量时,变量名不加美元符号($,PHP语言中变量需要),如: your_name="runoob.com" 注意,变量名和等号之间不能有空格,这可能和你熟悉的所有编程语言都不一 ...
- 用IDLE调试python程序
1. 设置断点 先放例子: import pdb a=1 b=10 pdb.set_trace()#这里是断点 c=a+b print(c) import pdb 后,用pdb.set_trace() ...
- JavaEE--分布式对象
参考:http://blog.csdn.net/smcwwh/article/details/7080997 1.客户与服务器的角色 所有分布式编程技术的基本思想都很简单:客户计算机产生一个请求,然后 ...
- tensorflow2使用中的一些问题
from tensorflow import keras import tensorflow as tf import numpy as np print(tf.__name__,tf.__versi ...
- redis day02 下
位图:是二进制数据(0101101010)2^32 强势点: 01_login :101110(比如:第一天登录,二天没登录) 传统的字符串解决方案中 记录用户登录日期 统计堪忧 01_login_ ...
- mac环境下创建bash_profile文件并写入内容 更改php环境变量
1. 启动终端Terminal 2. 进入当前用户的home目录 输入cd ~ 3. 创建.bash_profile 输入touch .bash_profile 4. 编辑.bash_profile文 ...
- 一、linux-mysql 运维DBA介绍
一.DBA数据库管理人员需要在整个架构中解决数据库的压力,前端业务通过扩展,加机器就可以很好的解决,但是存储.数据库就不是很好的可以进行扩展,数据也是分配不均的,所以,1)通过在数据库前面添加Memc ...
- 吴裕雄--天生自然python学习笔记:python 用 Open CV抓取摄像头视频图像
Open CV 除了可以读取.显示静态图片外 , 还可 以加载及播放动态影片, 以 及 读取内置或外接摄像头的图像信息 . 很多笔记本电脑都具有摄像头 , OpenCV 可通过 VideoC aptu ...
- django框架进阶-解决跨域问题
####################################### """ 一.为什么会有跨域问题? 是因为浏览器的同源策略是对ajax请求进行阻拦了,但是不 ...