Home >Java >javaTutorial >Java Concurrent Programming: Analysis of Usage Examples of AtomicInteger Atomic Integer of JUC Toolkit

Java Concurrent Programming: Analysis of Usage Examples of AtomicInteger Atomic Integer of JUC Toolkit

WBOY
WBOYforward
2023-04-25 22:22:30890browse

    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, AtomicIntegerThe 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!

    Statement:
    This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete