


Java Concurrent Programming: Analysis of Usage Examples of AtomicInteger Atomic Integer of JUC Toolkit
The AtomicInteger class stores an int value at the bottom and provides methods to perform atomic operations on the int value. AtomicInteger was introduced starting with Java 1.5 as part of the java.util.concurrent.atomic
package.
1. Basic usage of AtomicInteger
Through the following AtomicInteger
construction method, you can create an AtomicInteger
object. The initial value of the object defaults to 0. . AtomicInteger
Provides get and set methods to obtain the underlying int integer value and set the int integer value
//初始值为0的atomicInteger对象 AtomicInteger atomicInteger = new AtomicInteger(); //初始值为200的atomicInteger对象 AtomicInteger atomicInteger = new AtomicInteger(200); int currentValue = atomicInteger.get(); //100 atomicInteger.set(2453); //现在的值是 2453
However, the above method is not suitable for AtomicInteger
The core content, AtomicInteger
The core content is reflected in its atomicity, which we will introduce below.
2. When do you need to use AtomicInteger
We usually use it in the following two scenariosAtomicInteger
To operate a counter in a multi-threaded concurrent scenario , it is necessary to ensure the atomicity of counter operations.
Compare values. If the given value is equal to the current value, update the value and implement a non-blocking algorithm for the operation.
2.1. Atomic counter scenario
Use AtomicInteger
as a counter. AtomicInteger
provides several methods for atomic operations of addition and subtraction.
For example, to get a value from a map, use the get() method, which is the first operation; after getting the value, add n to the value, which is the second operation; the addition operation will be performed The third operation is to put the value into the map again. The so-called atomicity of operations means that in a multi-threaded concurrency scenario, the above three operations are atomic, that is, indivisible. There will be no situation where thread A gets the value and thread B also gets the value at the same time. The two threads perform operations on the value at the same time and put it in again one after another. This situation is not suitable for AtomicInteger
It will appear that AtomicInteger
operations are thread-safe and indivisible.
addAndGet()
- Add the given value to the current value and return the new value after the addition, ensuring the atomicity of the operation.
getAndAdd()
- Add the given value to the current value and return the old value, ensuring atomicity of the operation.
incrementAndGet()
- Increases the current value by 1 and returns the new value after the increment. It is equivalent to the i
operation and guarantees the atomicity of the operation.
getAndIncrement()
- Increase the current value by 1 and return the old value. Equivalent to the i
operation and ensuring the atomicity of the operation.
decrementAndGet()
- Subtract 1 from the current value and return the new value after subtraction, which is equivalent to the i--
operation and guarantees the atomicity of the operation sex.
getAndDecrement()
- Subtract 1 from the current value and return the old value. It is equivalent to the --i
operation and guarantees the atomicity of the operation.
The following is an example of the atomic operation method of AtomicInteger
public class Main { public static void main(String[] args) { //初始值为100的atomic Integer AtomicInteger atomicInteger = new AtomicInteger(100); System.out.println(atomicInteger.addAndGet(2)); //加2并返回102 System.out.println(atomicInteger); //102 System.out.println(atomicInteger.getAndAdd(2)); //先获取102,再加2 System.out.println(atomicInteger); //104 System.out.println(atomicInteger.incrementAndGet()); //加1再获取105 System.out.println(atomicInteger); //105 System.out.println(atomicInteger.getAndIncrement()); //先获取105再加1 System.out.println(atomicInteger); //106 System.out.println(atomicInteger.decrementAndGet()); //减1再获取105 System.out.println(atomicInteger); //105 System.out.println(atomicInteger.getAndDecrement()); //先获取105,再减1 System.out.println(atomicInteger); //104 } }
2.2. Numeric comparison and exchange operation
compareAndSet operation compares the contents of a memory location with a given value A comparison is made, and only if they are identical, the contents of that memory location are modified to a given new value. This process is completed as a single atomic operation.
compareAndSet method: If the current value == expected value, set the value to the given updated value.
boolean compareAndSet(int expect, int update)
expect
is the expected value
update
is the updated value
AtomicInteger compareAndSet() method example
import java.util.concurrent.atomic.AtomicInteger; public class Main { public static void main(String[] args) { //初始值为100的atomic Integer AtomicInteger atomicInteger = new AtomicInteger(100); //当前值100 = 预期值100,所以设置atomicInteger=110 boolean isSuccess = atomicInteger.compareAndSet(100,110); System.out.println(isSuccess); //输出结果为true表示操作成功 //当前值110 = 预期值100?不相等,所以atomicInteger仍然等于110 isSuccess = atomicInteger.compareAndSet(100,120); System.out.println(isSuccess); //输出结果为false表示操作失败 } }
3. Summary
AtomicInteger
can help us achieve thread safety and atomicity of int numerical operations in multi-thread scenarios without using synchronized synchronization locks. And using AtomicInteger
to implement atomic operations on int values is far more efficient than using synchronized synchronization locks.
java.util.concurrent.atomic
package not only provides us with AtomicInteger
, but also provides the AtomicBoolean Boolean atomic operation class and the 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.
The above is the detailed content of Java Concurrent Programming: Analysis of Usage Examples of AtomicInteger Atomic Integer of JUC Toolkit. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.
