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语言中,增量操作符(++)不是原子的,也就 ...
随机推荐
- 基于SpringBoot框架企业级应用系统开发全面实战
Eclipse 安装spring-tool-suite教程,并创建一个新的springboot项目 使用SpringBoot构建项目,加载SSM整合的applicationContext.xml的注解 ...
- Java 10按钮设计(awt)
/** * 2019年8月9日08:03:41 * 目的:利用Java设计10个按钮 * @author 张涛 * */ //导入awt包 import java.awt.*; import java ...
- oracle sql语句学习(一)
oraclexe 11.0.2.0 输出到文件 SQL>spool /*完整路径*/; SQL>spool off; 多表自然链接 select spj.sno from spj join ...
- R 画地图
R 绘制中国省市分布地图 library(maps) library(mapdata) library(maptools); getColor=function(mapdata,provname,pr ...
- hibernate 持久化对象 save
hibernate 持久化对象 save new出来的user对象是游离状态的对象,执行session.save()方法保存后,user对象就变为持久化了,持久化的对象跟数据库表双向绑定的意思, 对象 ...
- Spring IOC 和AOP
Spring是什么? Spring是一个轻量级的IoC和AOP容器框架. IOC:IOC就是控制反转,控制反转指的是把创建对象和管理对象之间的依赖关系交给了IOC容器来管理.以前new对象由程序员来控 ...
- Angular(二)
Angular开发者指南(二)概念概述 template(模板):带有附加标记的模板HTMLdirectives(指令):使用自定义属性和元素扩展HTMLmodel(模型):用户在视图中显示的数据 ...
- springboot集成aop日志
日常开发中假如是前后端完全分离,我们会习惯用浏览器去调用controller的接口来测试.这一个过程普通的日志功能会记录sql参数等一些基本信息.但是假如项目越来越庞大,我们的包越来越多,在维护项目和 ...
- mysql字段值为null时排序问题
-- DESC 降序时候默认null值排在后面.ASC升序时默认null值排在前面,可使用 IS NULL处理 ORDER BY score desc,gmPrice IS NULL,gmPrice, ...
- Linux_拷贝,剪切,删除和创建文件
cp 你要拷贝的文件 + 目录/带路径的文件名(在拷贝的同时,让这个文件重新命名) cp /tep/dir01 ~ 代表将dir01拷贝到当前用户的家目录中 cp /tep/dir02 ~/di ...