AtomicInteger属于Atomic Variables族。 主要好处是使用它不会阻塞而不是进行阻塞同步,因此避免了线程的挂起和重新调度。

AtomicInteger基于“比较和交换”机制,并且是原子变量的标量组的一部分。

我们的第一个用例是可以多次访问的网页上的功能。

 package com.gkatzioura.concurrency;  import java.util.concurrent.atomic.AtomicInteger;  public class AtomicIntegerExample { private AtomicInteger atomicInteger = new AtomicInteger(); public void serveRequest() { atomicInteger.incrementAndGet(); /** * logic */ } public int requestsServed() { return atomicInteger.get(); }  } 

并测试我们的用例

 package com.gkatzioura.concurrency;  import java.util.ArrayList;  import java.util.List;  import java.util.concurrent.ExecutionException;  import java.util.concurrent.ExecutorService;  import java.util.concurrent.Executors;  import java.util.concurrent.Future;  import org.junit.jupiter.api.Assertions;  import org.junit.jupiter.api.BeforeEach;  import org.junit.jupiter.api.Test;  public class AtomicIntegerExampleTest { private AtomicIntegerExample atomicIntegerExample; @BeforeEach void setUp() { atomicIntegerExample = new AtomicIntegerExample(); } @Test void testConcurrentIncrementAndGet() throws ExecutionException, InterruptedException { final int threads = 10 ; ExecutorService executorService = Executors.newFixedThreadPool(threads); List<Future> futures = new ArrayList(); for ( int i = 0 ; i { atomicIntegerExample.serveRequest(); return null ; })); } for (Future future: futures) { future.get(); } Assertions.assertEquals( 10 ,atomicIntegerExample.requestsServed()); }  } 

除了使用原子整数作为计数器之外,您还可以在各种情况下使用它。 例如线程安全的循环算法。

 package com.gkatzioura.concurrency;  import java.util.concurrent.atomic.AtomicInteger;  public class AtomicIntegerRoundRobin { private final int totalIndexes; private final AtomicInteger atomicInteger = new AtomicInteger(- 1 ); public AtomicIntegerRoundRobin( int totalIndexes) { this .totalIndexes = totalIndexes; } public int index() { int currentIndex; int nextIndex; do { currentIndex = atomicInteger.get(); nextIndex = currentIndex< Integer.MAX_VALUE ? currentIndex+ nextIndex = currentIndex< Integer.MAX_VALUE ? currentIndex+ 1 : 0 ; } while (!atomicInteger.compareAndSet(currentIndex, nextIndex)); return nextIndex % totalIndexes; }  } 

totalIndex是索引的总数。 当请求下一个索引的请求时,计数器将增加,并进行比较和设置操作。 如果由于另一个线程而失败,则它将再次尝试该操作,并将获得计数器的下一个值。
模运算将给出当前索引。 如果原子整数达到最大值,则应将其重置为零。 重置会导致边缘情况并更改索引的顺序。 如果这是一个问题,则可以根据总索引大小来调整最大值以避免这种情况。

还对此进行了一些测试。

 package com.gkatzioura.concurrency;  import java.util.ArrayList;  import java.util.List;  import java.util.concurrent.ExecutionException;  import java.util.concurrent.ExecutorService;  import java.util.concurrent.Executors;  import java.util.concurrent.Future;  import org.junit.jupiter.api.Assertions;  import org.junit.jupiter.api.BeforeEach;  import org.junit.jupiter.api.Test;  AtomicIntegerRoundRobinTest { class AtomicIntegerRoundRobinTest { private static final int MAX_INDEX = 10 ; private AtomicIntegerRoundRobin atomicIntegerRoundRobin; @BeforeEach void setUp() { atomicIntegerRoundRobin = new AtomicIntegerRoundRobin(MAX_INDEX); } @Test void testIndexesSerially() { for ( long i= 0 ;i<MAX_INDEX* 20 ;i++) { System.out.println(atomicIntegerRoundRobin.index()); } Assertions.assertEquals( 0 , atomicIntegerRoundRobin.index()); } @Test void testIndexesConcurrently() throws ExecutionException, InterruptedException { ExecutorService executorService = Executors.newFixedThreadPool( 4 ); List<Future> futures = new ArrayList(); for ( int i = 0 ; i atomicIntegerRoundRobin.index())); } for (Future future: futures) { System.out.println(future.get()); } Assertions.assertEquals( 0 ,atomicIntegerRoundRobin.index()); }  } 

翻译自: https://www.javacodegeeks.com/2019/11/atomicinteger-on-java-and-round-robin.html

Java和Round-Robin上的AtomicInteger相关推荐

  1. Round Robin 算法

    什么是Round Robin? 先来看和他相近的名词,轮询调度算法(Round-Robin Scheduling) 轮询调度算法的原理是每一次把来自用户的请求轮流分配给内部中的服务器,从1开始,直到N ...

  2. 负载均衡算法--轮询法(Round Robin)

    在分布式系统中,为了实现系统的高性能.高并发.高可用,在构架中都会进行负载均衡设计,它是分布式系统的核心和中枢,负载均衡的好坏直接影响着整个系统的性能.负载均衡分为软件均衡和硬件均衡两类,比如apac ...

  3. Round Robin 概念理解

    什么是Round Robin? 先来看和他相近的名词,轮询调度算法(Round-Robin Scheduling) 轮询调度算法的原理是每一次把来自用户的请求轮流分配给内部中的服务器,从1开始,直到N ...

  4. 负载均衡算法--加权轮询法(Weight Round Robin)

    接上一篇博文:负载均衡算法–轮询法(Round Robin),本文讲解加权轮询算法. 加权轮询算法:不同的后端服务器可能机器的配置和当前系统的负载并不相同,因此它们的抗压能力也不相同.给配置高.负载低 ...

  5. round robin权重轮循算法实现

    为什么80%的码农都做不了架构师?>>>    先上代码,采用php脚本语言 <?php/* * Copyright (C) FatHong*//* 数据初始化,weight: ...

  6. Nginx负载均衡的4种方式 :轮询-Round Robin 、Ip地址-ip_hash、最少连接-least_conn、加权-weight=n

    负载均衡的概念: Load Balance负载均衡是用于解决一台机器(一个进程)无法解决所有请求而产生的一种算法. 我们知道单台服务器的性能是有上限的,当流量很大时,就需要使用多台服务器来共同提供服务 ...

  7. Java实例教程(上)

    第一个Java程序 Java 枚举 Java注释 Java创建对象 Java访问实例变量和方法 Java局部变量实例 Java编译错误 Java 实例变量示例 Java类变量 静态变量示例 Java静 ...

  8. 仲裁器设计(二)-- Round Robin Arbiter 轮询调度算法

    作者:李虹江 原文:https://mp.weixin.qq.com/s/r-nckE5nGz9mc5KqjPXKYg 本文授权转自IC加油站微信号,未经作者授权,严禁二次转载. 上一篇老李讲了固定优 ...

  9. Round robin

    本篇文章先讲述轮询调度算法 (Round-Robin)及其在此基础上改进型的权重轮询算法 (Weighted Round-Robin). 轮询调度算法(Round-Robin Scheduling) ...

  10. Verilog权重轮询仲裁器设计——Weighted Round Robin Arbiter

    前两篇讲了固定优先级仲裁器的设计.轮询仲裁器的设计 Verilog固定优先级仲裁器--Fixed Priority Arbiter_weixin_42330305的博客-CSDN博客 Verilog轮 ...

最新文章

  1. 函数 tostring_Kotlin实战之Fuel的高阶函数
  2. linux进程间通讯-消息队列
  3. 运算服务器v9型号,v9云服务器
  4. java int数组写入文件中_Java程序将int数组写入文件
  5. gg参数:dblogreader
  6. RowTime field should not be null, please convert it to a non-null long value.
  7. 破解mysql数据库的密码
  8. 软件工程--第一周学习进度
  9. SpringMVC 通过post接收form参数或者json参数
  10. SqlServer判断数据库、表、字段、存储过程、函数是否存在
  11. 问题四十二:怎么用ray tracing画任意圆环片段
  12. Trisk:在 Flink 实现以 task 为中心的流处理动态 Reconfiguration 的 Control Plane
  13. “FreeTextBox”控件使用——Word编辑器
  14. 【无标题】学生成绩管理系统
  15. Arranging Coins 排列硬币
  16. 游戏阴阳师启动闪退问题解决
  17. 历代iOS设备屏幕分辨率
  18. 头歌实践教学平台 MIPS CPU设计(HUST)
  19. vue2引用typeScript的步骤
  20. 基于自注意力的生成对抗归因网络的交通流缺失数据修复

热门文章

  1. jzoj5223-B【矩阵乘法】
  2. Hadoop生态hive(四)数据类型
  3. Hadoop的FileSystem.copyToLocalFile两个参数 空指针异常
  4. TCP为什么是三次握手和四次挥手
  5. 跟我学 Java 8 新特性之 Stream 流(七)流与迭代器,流系列大结局
  6. React不提交表单并且获取表单中的数据
  7. SparkContext源码分析
  8. idea报错:Error:java: JDK isn‘t specified for module ‘xxx‘
  9. rabbitmq-通配符模式
  10. 特权级概述(哥子就想知道CPU是如何验证特权级的)GATE+TSS