Java Concurrent Programming JUC Chapter 12: atomicinteger atomic integer

Letter brother blog 2021-04-08 07:45:14
java concurrent programming juc chapter


AtomicInteger The underlying class stores a int value , And provide the method for the int Value for atomic operation .AtomicInteger As java.util.concurrent.atomic Part of the package , from Java 1.5 Start introducing .

1. AtomicInteger Basic usage

Through the AtomicInteger Construction method , You can create a AtomicInteger object , The initial value of the object defaults to 0.AtomicInteger Provide get and set Method , Get the bottom layer int An integer value , With the setting int An integer value

// The initial value is 0 Of atomicInteger object 
AtomicInteger atomicInteger = new AtomicInteger();
// The initial value is 200 Of atomicInteger object 
AtomicInteger atomicInteger = new AtomicInteger(200);
int currentValue = atomicInteger.get(); //100
atomicInteger.set(2453); // Now the value is zero 2453

But the above method , about AtomicInteger It's not at the core of it in terms of content ,AtomicInteger The core content is its atomicity , Let's talk about .

2. When you need to use AtomicInteger

We usually use it in the following two scenarios AtomicInteger

  1. Operating a counter in a multithreaded concurrent scenario , The atomicity of counter operation needs to be guaranteed .
  2. Make a numerical comparison , If the given value is equal to the current value , Update the value , And realize the non blocking algorithm of operation .

2.1. Atomic counter scenario

hold AtomicInteger Use as a counter ,AtomicInteger Some methods of addition are provided 、 The atomic operation of subtraction .

For example, from a map Get value inside , use get() Method , This is the first operation ; After getting the value, add n, This is the second operation ; The value that will be added , Put in... Again map Inside is the third operation . The atomicity of operation means : In the scenario of multithreading concurrency , The above three operations are atomic , It's indivisible . There will be no A Threads get The numerical value is obtained ,B Threads also get At this point , Two threads operate on the value at the same time and put it in again , This is the case for AtomicInteger It's not going to happen ,AtomicInteger Operations are thread safe 、 Indivisible .

  • addAndGet()- Add the given value to the current value , And returns a new value after addition , And guarantee the atomicity of the operation .
  • getAndAdd()- Add the given value to the current value , And return the old value , And guarantee the atomicity of the operation .
  • incrementAndGet()- Increase the current value by 1, And returns a new value after adding . It is equivalent to ++i operation , And guarantee the atomicity of the operation .
  • getAndIncrement()- Increase the current value by 1 And return the old value . amount to ++i operation , And guarantee the atomicity of the operation .
  • decrementAndGet()- Subtract... From the current value 1, And return a new value after subtraction , amount to i-- operation , And guarantee the atomicity of the operation .
  • getAndDecrement()- Subtract... From the current value 1, And return the old value . It is equivalent to --i operation , And guarantee the atomicity of the operation .

Here is AtomicInteger Examples of atomic manipulation

public class Main {
public static void main(String[] args) {
// The initial value is 100 Of atomic Integer
AtomicInteger atomicInteger = new AtomicInteger(100);
System.out.println(atomicInteger.addAndGet(2)); // Add 2 And back to 102
System.out.println(atomicInteger); //102
System.out.println(atomicInteger.getAndAdd(2)); // First get 102, add 2
System.out.println(atomicInteger); //104
System.out.println(atomicInteger.incrementAndGet()); // Add 1 Get more 105 
System.out.println(atomicInteger); //105 
System.out.println(atomicInteger.getAndIncrement()); // First get 105 add 1
System.out.println(atomicInteger); //106
System.out.println(atomicInteger.decrementAndGet()); // reduce 1 Get more 105
System.out.println(atomicInteger); //105
System.out.println(atomicInteger.getAndDecrement()); // First get 105, Re reduction 1
System.out.println(atomicInteger); //104
}
}

2.2. Numerical comparison and exchange operation

compareAndSet Operation compares the contents of a memory location with a given value , Only when they are the same , Will change the contents of the memory location to a given new value . This process is done in the form of a single atomic operation .

compareAndSet Method : If Current value == Expected value , Then set the value to the given update value .

boolean compareAndSet(int expect, int update)
  • expect It's the expected value
  • update Is the update value

AtomicInteger compareAndSet() Examples of methods

import java.util.concurrent.atomic.AtomicInteger;
public class Main {
public static void main(String[] args) {
// The initial value is 100 Of atomic Integer
AtomicInteger atomicInteger = new AtomicInteger(100);
// Current value 100 = Expected value 100, So set atomicInteger=110
boolean isSuccess = atomicInteger.compareAndSet(100,110);
System.out.println(isSuccess); // The output is true Indicates the operation is successful 
// Current value 110 = Expected value 100? It's not equal , therefore atomicInteger Still equal to 110
isSuccess = atomicInteger.compareAndSet(100,120);
System.out.println(isSuccess); // The output is false Indicates that the operation failed 
}
}

3. summary

AtomicInteger Can help us in not using synchronized In the case of synchronous lock , Implementation in a multithreaded scenario int Thread safety of numerical operations , Atomicity of operation . And use AtomicInteger To achieve int Atomic manipulation of numbers , Far more than using synchronized Synchronous lock is more efficient . java.util.concurrent.atomic The bag not only provides us with AtomicInteger, It also provides AtomicBoolean Boolean atomic operation class 、AtomicLong Long integer Boolean atomic operation class 、AtomicReference Object atomic operation class 、AtomicIntegerArray Integer array atomic operation class 、AtomicLongArray Long integer array atomic operation class 、AtomicReferenceArray Object array atomic operation class .

Welcome to my blog , There are many collections of fine products in it

Reprint of this article indicates the source ( Must be connected , You can't just turn words ): Alphabet blog - zimug.com

If it helps you , Give me some compliments 、 Share ! Your support is my inexhaustible creative power ! . in addition , The author recently output the following fine content , Looking forward to your attention .

版权声明
本文为[Letter brother blog]所创,转载请带上原文链接,感谢
https://javamana.com/2021/04/20210408074411402j.html

  1. Spring Boot 中如何统一 API 接口响应格式?
  2. 深入分析 SpringMVC 参数解析器
  3. SpringBoot 中如何自定义参数解析器?
  4. SpringMVC 初始化流程分析
  5. 如何优雅的实现 Spring Boot 接口参数加密解密?
  6. Spring5 里边的新玩法!这种 URL 请求让我涨见识了!
  7. SpringMVC 中的参数还能这么传递?涨姿势了!
  8. 手把手教你开发 MyBatis 插件
  9. 细品 Spring Boot+Thymeleaf,还有这么多好玩的细节!
  10. Spring Boot 日志各种使用姿势,是时候捋清楚了!
  11. Deep analysis of viewresolver of nine components of spring MVC
  12. In depth analysis of handleradapter of nine components of spring MVC
  13. In depth analysis of handlermapping of nine components of spring MVC
  14. Can spring boot define interface methods to be declared private?
  15. Dispatcherservlet of spring MVC source code analysis
  16. Framework servlet for spring MVC source code analysis
  17. How to unify API response format in spring boot?
  18. In depth analysis of spring MVC parameter parser
  19. How to customize parameter parser in springboot?
  20. Analysis of spring MVC initialization process
  21. How to realize encryption and decryption of spring boot interface parameters gracefully?
  22. A new way to play in spring 5! This kind of URL request makes me see better!
  23. Can parameters in spring MVC be passed like this? It's up!
  24. Hand in hand to teach you how to develop mybatis plug-ins
  25. Fine spring boot + thymeleaf, there are so many fun details!
  26. Spring boot logs all kinds of posture, it's time to clear!
  27. Web 3.0踏浪而来,分布式存储举足轻重|时空云邀请您参加Web3.0中国峰会暨分布式存储行业大会
  28. spring-aop 进不了切面方法的解决办法
  29. Web 3.0 is coming, distributed storage is very important | spatiotemporal cloud invites you to attend Web3.0 China Summit and distributed storage industry conference
  30. The solution of spring AOP can't enter the section method
  31. Linux中如何启用root用户
  32. How to enable root in Linux
  33. 踩坑 MySQL 索引,看看你真的会用吗?
  34. Hive优化之配置参数的优化(一)
  35. Step on the MySQL index to see if you really know how to use it?
  36. Optimization of configuration parameters for hive optimization (1)
  37. Linux入门教程资料分享
  38. Introduction to Linux
  39. 外部连接mysql docker容器异常
  40. Exception of external connection MySQL docker container
  41. Zookeeper分布式锁?
  42. Zookeeper distributed lock?
  43. 嵌入式Linux_Framebuffer_03点阵显示ASCII字符串
  44. 嵌入式Linux_Framebuffer_02字符编码
  45. Embedded Linux_ Framebuffer_ 03 dot matrix display ascii string
  46. Embedded Linux_ Framebuffer_ 02 character encoding
  47. Looking forward to new product launch of Xiaomi in spring CNMO takes you to see 11 new products in advance
  48. An inventory of the commonly used garbage collectors in Java
  49. Why is it so easy to get started with HBase?
  50. Implementation of PRC framework based on netty
  51. 2021 Java back end engineer must know knowledge - (Dubbo, distributed RPC framework)
  52. 关于spring advisor和元数据 同时来管理事务的问题
  53. How to manage transactions with spring advisor and metadata at the same time
  54. 使用Playwright对Java API实现自动视觉测试 - applitools
  55. Using playwright to implement automatic visual testing for Java API - applitools
  56. Dubbo和Spring cloud、Istio对比图
  57. Comparison of Dubbo with spring cloud and istio
  58. HttpServletRequest、通过request获得请求头、请求体等、解决中文乱码等问题
  59. Mybatis学习笔记-一对一,一对多,多对多关联查询
  60. Mybatis学习笔记-基本概念与操作