当前位置:网站首页>源码学习:AtomicInteger类代码内部逻辑
源码学习:AtomicInteger类代码内部逻辑
2022-06-26 12:35:00 【网小鱼的学习笔记】
1. AtomicInteger是什么
一个可以原子更新的int值。有关原子变量属性的描述,请参阅java.util.concurrent.atomic包规范。AtomicInteger用于原子递增计数器等应用程序,不能用作Integer的替代品。但是,这个类确实扩展了Number,以允许处理基于数字的类的工具和实用程序进行统一访问。
2. 设置使用CAS进行更新
setUp to use Unsafe.compareAndAwapInt for update
3. 计算偏移量
检查用户权限获取声明为公有的字段,然后根据有权限的字段,获取系统的偏移量value得到一个long类型的偏移量的值
static {
try {
valueOffset = unsafe.objectFieldOffset
(AtomicInteger.class.getDeclaredField("value"));
} catch (Exception ex) {
throw new Error(ex); }
}
4. 懒赋值
/** * 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);
}
5. getAndSet 先获取然后再进行赋值操作(涉及CAS)
public final int getAndSetInt(Object var1, long var2, int var4) {
int var5;
do {
var5 = this.getIntVolatile(var1, var2);
} while(!this.compareAndSwapInt(var1, var2, var5, var4));
return var5;
}
第一步:传入一个要替换的值var5;然后计算根据var1和war2通过getIntVolatile计算得到var5
第二步:如果compareAndSwapInt比较结果和var5相等,返回var5
6. compareAndSet
/** * 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 {@code 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);
}
如果实际要更新的值和预期要更新的值不想等则返回false,如果实际要更新的值和期待值相等返回true
7. 获取并更新值
第一步:
/** * 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) {
return unsafe.getAndAddInt(this, valueOffset, delta) + delta;
}
第二步:
public final int getAndAddInt(Object var1, long var2, int var4) {
int var5;
do {
var5 = this.getIntVolatile(var1, var2);
} while(!this.compareAndSwapInt(var1, var2, var5, var5 + var4));
return var5;
}
如果原来值var1和偏移量var2得到的计算和结果var5相等,给var5加上相应的增量delta即var4
8.getAndUpdate
public final int getAndUpdate(IntUnaryOperator updateFunction) {
int prev, next;
do {
prev = get();
next = updateFunction.applyAsInt(prev);
} while (!compareAndSet(prev, next));
return prev;
}
用应用给定函数的结果原子地更新当前值,返回跟新前的值。该函数应该没有副作用,因为当线程争用导致尝试更新失败时,会重新尝试更新。
9.updateAndGet
public final int updateAndGet(IntUnaryOperator updateFunction) {
int prev, next;
do {
prev = get();
next = updateFunction.applyAsInt(prev);
} while (!compareAndSet(prev, next));
return next;
}
用应用给定函数的结果原子地更新当前值,返回跟新后的值。该函数应该没有副作用,因为当线程争用导致尝试更新失败时,会重新尝试更新。
10.getAndAccumulate
public final int getAndAccumulate(int x, IntBinaryOperator accumulatorFunction) {
int prev, next;
do {
prev = get();
next = accumulatorFunction.applyAsInt(prev, x);
} while (!compareAndSet(prev, next));
return prev;
}
用将给定函数应用于当前值和给定值的结果原子地更新当前值,返回更新前的值。该函数应该没有副作用,因为当线程争用导致尝试更新失败时,可能会重新应用该函数。函数的第一个参数是当前值,第二个参数是给定的更新。
11. accumulateAndGet
public final int accumulateAndGet(int x, IntBinaryOperator accumulatorFunction) {
int prev, next;
do {
prev = get();
next = accumulatorFunction.applyAsInt(prev, x);
} while (!compareAndSet(prev, next));
return next;
}
用将给定函数应用于当前值和给定值的结果原子地更新当前值,返回跟新后的值。该函数应该没有副作用,因为当线程争用导致尝试更新失败时,可能会重新应用该函数。函数的第一个参数是当前值,第二个参数是给定的更新。
边栏推荐
- Ubuntu安装配置PostgreSQL(18.04)
- I want to know whether flush is a stock market? Is online account opening safe?
- Assembly language (7) operation instruction
- PHP laravel+gatewayworker completes im instant messaging and file transfer functions (Chapter 2: explanation of business logic)
- UDP protocol details [easy to understand]
- VMware虚拟机 桥接模式 无法上网 校园网「建议收藏」
- 由错误<note: candidate expects 1 argument, 0 provided>引发的思考
- Msvcr110 not found DLL, unable to continue code execution Solution for startup
- Research and development practice of Kwai real-time data warehouse support system
- 710. 黑名单中的随机数
猜你喜欢
![[solved] data duplication or data loss after laravel paginate() paging](/img/68/7bf51bbf893a91bee24f5f7d4a369f.jpg)
[solved] data duplication or data loss after laravel paginate() paging

JMeter response time and TPS listener tutorial

Xiaolong 888 was released, Xiaomi 11 was launched, and 14 manufacturers carried it in the first batch!

The laravel dingo API returns a custom error message
![[redis series] redis learning 16. Redis Dictionary (map) and its core coding structure](/img/d2/a6cbb0abe9e04c412d1f6021430528.png)
[redis series] redis learning 16. Redis Dictionary (map) and its core coding structure

"Pinduoduo and short video speed version", how can I roast!

PHP laravel+gatewayworker completes im instant messaging and file transfer (Chapter 1: basic configuration)

Tiger DAO VC产品正式上线,Seektiger生态的有力补充

Vscode solves the problem of Chinese garbled code

Redis learning - 02 common data types, operation commands and expiration time
随机推荐
2022 edition of investment analysis and "fourteenth five year plan" development prospect forecast report of China's switchgear industry
NoSQL mongodb - 01 introduction to NoSQL and mongodb
栈,后入先出
Laravel subdomain accesses different routing files and different modules
JMeter response time and TPS listener tutorial
Tiger Dao VC products are officially launched, a powerful supplement to seektiger ecology
Redis learning - 02 common data types, operation commands and expiration time
PHP laravel+gatewayworker completes im instant messaging and file transfer (Chapter 1: basic configuration)
Analysis report on China's photovoltaic inverter market prospect forecast and investment strategy recommendations in 2022
PHP laravel+gatewayworker completes im instant messaging and file transfer functions (Chapter 2: explanation of business logic)
2022 edition of China's medical robot industry investment status investigation and prospect dynamic analysis report
Nodejs framework express and KOA
TP5 thinkphp5 extension package think Mongo operation mongodb time interval range query
Ubuntu安装配置PostgreSQL(18.04)
2022 edition of Beijing 5g industry investment planning and development prospect forecast analysis report
PHP unit conversion
How long ago did PHP get
BigInt:处理大数字(任意长度的整数)
MySQL optimization - index (what is an index?)
PHP calculates excel coordinate values, starting with subscript 0