【Java原理系列】 AtomicInteger原理用法源码详解

java线程-AtomicInteger原子类实现原理 上面的代码并非线程安全的,问题主要出现在count变量的不可见性和count+=1并非原子性操作,之前的解决方式都是使用Synchronized或者java sdk加锁的方式来保证原子性,使用volatile来保证可见性。在java线程-Lock详解&AQS原理详解一文中,发现大量使用了自旋+CAS操作,来保证线程安全性,这是一种无锁的操作,性能会比加锁的方式高很多。 阅读详情

Java AtomicInteger原理用法源码详解

基本原理

Java 中的 AtomicInteger 是一个原子类,用于实现对整数类型的原子操作。它提供了一系列方法,如 get()、set()、incrementAndGet()、compareAndSet() 等,可以在多线程环境下安全地进行原子操作。通过使用 AtomicInteger,可以避免使用显式的锁来保护共享整数变量,从而提高并发性能。它适用于许多并发场景,如计数器、标记位等。

AtomicInteger 的原理基于 CAS(Compare-And-Swap)操作。它内部使用了 Unsafe 类或者其他底层的原子操作机制来实现线程安全的操作。通过 CAS 操作,AtomicInteger 可以保证在多线程环境下对整数值的修改是原子性的,避免了竞态条件和数据不一致等问题。

AtomicInteger 的主要特点和原理如下:

  1. 内部使用 volatile 修饰的 int 变量:AtomicInteger 内部有一个被 volatile 修饰的 int 变量,用于存储整数值。volatile 关键字确保了变量的可见性,使得对该变量的读写操作具有原子性。
  2. 使用 CAS 操作进行原子更新:AtomicInteger 中的原子操作方法都是基于 CAS 操作实现的。CAS 操作包括比较内存中的值与预期值是否相等,如果相等则更新为新值,否则操作失败。CAS 操作利用底层硬件提供的原子指令,确保操作的原子性。
  3. 循环重试:由于 CAS 操作可能在多线程环境下失败,因此 AtomicInteger 在实现中使用了循环重试的机制。如果 CAS 操作失败,它会不断尝试进行 CAS 操作,直到成功为止。

注意事项

  • AtomicInteger 并不能完全替代 Integer 类,因为它并没有提供自动装箱和拆箱的功能。

  • 虽然 AtomicInteger 提供了原子操作,但仍然需要根据具体情况考虑原子类的使用范围和正确性。有时候,可能需要额外的同步手段来保证一些复合操作的原子性。

    假设需要对一个计数器进行原子递增和条件检查,以决定是否执行某个操作。以下是一个示例代码:

if (counter.incrementAndGet() >= threshold) {
// 执行操作
}


尽管递增操作和条件检查各自都是原子的,但由于两个操作之间存在竞态条件,可能会导致结果不一致。因为在判断条件后,其他线程可能已经对计数器进行了修改。在这种情况下,可以使用额外的同步手段,如锁(`synchronized`)或者显示的使用 `Lock` 接口,来保证多个操作的原子性,可以确保递增操作、条件检查和操作的执行之间是原子的,避免了竞态条件。

```java
synchronized (lock) {
  if (counter.incrementAndGet() >= threshold) {
      // 执行操作
  }
}

基本方法

以下是对 AtomicInteger 类中提供的方法进行总结:

  • AtomicInteger(int initialValue):使用给定的初始值创建一个新的 AtomicInteger 对象。

  • AtomicInteger():创建一个新的 AtomicInteger 对象,并将初始值设为 0。

  • int get():获取当前存储的整数值。

  • void set(int newValue):设置整数值为指定的新值。

  • void lazySet(int newValue):最终将整数值设置为指定的新值。不保证立即生效,可能会延迟。

  • int getAndSet(int newValue):将整数值设置为指定的新值,并返回先前的值。

  • boolean compareAndSet(int expect, int update):如果当前值等于预期值,则原子地将整数值设置为指定的新值,并返回操作是否成功。

  • boolean weakCompareAndSet(int expect, int update):与 compareAndSet() 方法类似,但不提供强有力的保证和排序保证。

  • int getAndIncrement():先返回当前值,然后将整数值增加 1。

  • int getAndDecrement():先返回当前值,然后将整数值减少 1。

  • int getAndAdd(int delta):先返回当前值,然后将整数值增加指定的增量。

  • int incrementAndGet():将整数值增加 1,然后返回更新后的值。

  • int decrementAndGet():将整数值减少 1,然后返回更新后的值。

  • int addAndGet(int delta):将整数值增加指定的增量,然后返回更新后的值。

  • int getAndUpdate(IntUnaryOperator updateFunction):先获取当前值,然后将整数值更新为通过应用给定函数得到的新值,返回先前的值。

  • int updateAndGet(IntUnaryOperator updateFunction):先获取当前值,然后将整数值更新为通过应用给定函数得到的新值,返回更新后的值。

  • int getAndAccumulate(int x, IntBinaryOperator accumulatorFunction):先获取当前值,然后将整数值与给定值通过应用给定函数进行累积计算,返回先前的值。

  • int accumulateAndGet(int x, IntBinaryOperator accumulatorFunction):先获取当前值,然后将整数值与给定值通过应用给定函数进行累积计算,返回更新后的值。

  • String toString():以字符串形式返回当前存储的整数值。

  • int intValue():将当前存储的整数值转换为 int 类型并返回。

  • long longValue():将当前存储的整数值转换为 long 类型并返回。

  • float floatValue():将当前存储的整数值转换为 float 类型并返回。

  • double doubleValue():将当前存储的整数值转换为 double 类型并返回。

这些方法允许原子地对整数值进行各种操作,确保在多线程环境下的线程安全性。

场景示例

以下是几个适用场景和示例:

  1. 计数器(Counter):AtomicInteger 可以用作计数器,在多线程环境下实现原子的自增、自减操作。例如,统计网站访问次数或任务完成数量等。
public class Counter {
   
   
    private AtomicInteger count = new AtomicInteger(0);

    public void increment() {
   
   
        count.incrementAndGet();
    }

    public void decrement() {
   
   
        count.decrementAndGet();
    }

    public int getCount() {
   
   
        return count.get();
    }
}
  1. 并发任务处理:在并发任务处理中,可以使用 AtomicInteger 来控制任务的执行顺序或限制同时执行的任务数量。
import java.util.concurrent.atomic.AtomicInteger;

public class TaskProcessor {
   
   
    private static final int MAX_CONCURRENT_TASKS = 10;
    private AtomicInteger activeTasks = new AtomicInteger(0);

    public void processTask(Runnable task) {
   
   
        // 检查是否达到最大并发任务数
        while (activeTasks.get() >= MAX_CONCURRENT_TASKS) {
   
   
            // 等待其他任务完成后再继续执行
            
【项目实战】并发编程之AtomicInteger入门介绍 AtomicInteger是一种原子类型的数据结构,它可以用于实现并发编程中的原子操作。原子操作是指一个操作在执行过程中不会被其他线程干扰,要么完全执行成功,要么完全不执行。 阅读详情

相关推荐

Java中的原子操作:AtomicInteger函数详解

在多线程编程中,原子操作是一种能够确保操作的完整性和一致性的操作方式。AtomicInteger为我们提供了一种线程安全的整数类型,可以进行原子操作,避免了多线程环境下的数据竞争和并发问题。通过AtomicInteger,我们可以在多线程环境下安全地进行整数的读取、写入和更新操作,避免了数据竞争和并发问题的发生。在示例代码中,我们使用了lambda表达式来定义一个简单的加法操作。除了自增和自减,AtomicInteger还提供了addAndGet()方法和getAndAdd()方法,用于原子性地加法操作。

2301_79365003的博客 793

当GO.db安装失败时,生物信息学新手应该知道的5个底层逻辑

本文为生物信息学新手提供了解决GO.db安装失败的5个关键底层逻辑,包括网络连接与镜像源设置、版本兼容性检查、依赖关系管理、SQLite存储机制理解以及调试技巧。特别针对Bioconductor的GO.db包安装问题,详细介绍了如何通过切换国内镜像、管理版本冲突和解决依赖问题来成功安装,帮助用户高效克服常见安装障碍。

weixin_29062823的博客 411

保姆级教程:在爱快iKuai虚拟机里装OpenWrt旁路由,实现去广告和特殊功能

本文提供在爱快iKuai虚拟机中安装OpenWrt旁路由的详细教程,帮助用户实现去广告和特殊功能扩展。通过分步指导,包括虚拟机配置、网络设置和功能优化,打造稳定高效的家庭网络环境,特别适合软路由爱好者和网络管理员。

weixin_31364787的博客 879

PT静态时序分析实战:从基础命令到高级报告解析

本文详细介绍了PT(PrimeTime)静态时序分析(STA)的实战技巧,从基础命令如pt_shell和report_timing的使用,到高级报告解析与问题排查。通过丰富的实例和脚本示例,帮助工程师快速掌握时序分析的核心技能,提升芯片设计验证效率。

weixin_29289821的博客 962

快速上手:网页版EggNOG功能注释全流程解析

本文详细解析了网页版EggNOG在蛋白序列功能注释中的全流程操作,从初识工具到实战技巧,涵盖FASTA格式处理、参数设置、结果解读及常见问题解决方案。特别适合生物信息学初学者快速掌握这一高效注释工具,提升非模式生物基因组研究的注释效率。

weixin_29310631的博客 196

以宠辱之戒写 SAP Fiori Elements,把标准能力当成身体,把扩展冲动当成大患

SAP Fiori Elements开发中常面临业务方追求"独特页面"的压力,但过度自定义会破坏框架价值。老子"宠辱若惊"的智慧提醒开发者:不应因用户称赞或批评而动摇架构原则。标准模板的价值在于确保业务语义、交互规范和后端服务的一致性。扩展应遵循官方API,将业务逻辑放在ABAP/CDS层而非前端控制器。成熟项目会平衡标准与定制,使用annotation表达UI行为,仅在必要时通过受支持的extension points进行增强,保持系统的长期可维护性。

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 1010

python实现纵横向拉开档次法 (附完整源码)

python实现纵横向拉开档次法 (附完整源码)

希望我的博客,能帮上你解决学习中工作中所遇到的问题 790

Coze智能体开发:工作流教程之解析文件概述

大模型本身并不具备文件读取和解析的能力,无法直接处理文件字节流。对于支持工具调用(Function calling)的模型,扣子提供插件功能来帮助大模型调用外部工具 API,拓展大模型的能力边界。扣子插件商店提供海量官方插件和第三方插件,例如链接读取插件可以将链接对应的文件内容解析为纯文本传递给大模型。

王国平的博客 1798

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

上一篇: 【Java原理系列】 Java ThreadLocal 原理源码详解
下一篇: 【Java原理系列】 Java ByteArrayInputStream 原理用法源码分析
BigDataMLApplication
博客等级 码龄11年 7363粉丝 565原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

BigDataMLApplication

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值