Atomic operation class summary, why is it more and more difficult to interview middle and senior posts in Java

Keywords: Java Back-end Interview Programmer

The implementation principle of AtomicLong is consistent with AtomicInteger, except that one is for long variables and the other is for int variables. How does the AtomicBoolean class update the boolean variable? The core method is compareandset method, and its source code is as follows:

public final boolean compareAndSet(boolean expect, boolean update) {

    int e = expect ? 1 : 0;

    int u = update ? 1 : 0;

    return unsafe.compareAndSwapInt(this, valueOffset, e, u);

} 

It can be seen that the compareAndSet method is actually first converted to integer variables of 0,1, and then implemented through the atomic update method compareAndSwapInt for int variables. It can be seen that the atomic package only provides three basic types of atomic update methods: boolean, int and long. Referring to the method of updating boolean, atomic update char, doule and float can also be implemented with similar ideas.

[](

)Atomic update array type

The classes in the atomic package that can update the elements in the array are:

  1. AtomicIntegerArray: atomic updates the elements in the integer array;

  2. AtomicLongArray: atom updates elements in long array;

  3. AtomicReferenceArray: atomic updates elements in an array of reference types

The usage of these classes is consistent. Let's summarize the common methods with AtomicIntegerArray:

  1. addAndGet(int i, int delta): add the elements with index I in the array to the input value by atomic update;

  2. getAndIncrement(int i): increase the element with index I in the array by 1 by atomic update;

  3. compareAndSet(int i, int expect, int update): updates the element at the position with index I in the array

It can be seen that the AtomicIntegerArray and AtomicInteger methods are basically the same, except that one more array index bit i will be specified in the AtomicIntegerArray method. Here is a simple example:

public class AtomicIntegerArrayDemo {



    private static int[] value = new int[]{1, 2, 3};

    private static AtomicIntegerArray integerArray = new AtomicIntegerArray(value);



    public static void main(String[] args) {

        //Add 5 to the element at index 1 in the array

        int result = integerArray.getAndAdd(1, 5);

        System.out.println(result);

        System.out.println(integerArray.get(1));

    }

} 

Output results

2

7 

Add 5 to the element at position 1 through getAndAdd method. From the result, it can be seen that the element with index 1 becomes 7, and the number returned by this method is 2 before addition.

[](

)Atomic update reference type

If atomic updating of reference type variables is required, atomic also provides related classes to ensure thread safety:

  1. AtomicReference: atomic update reference type;

  2. Atomicreferencefield updater: updates the fields in the atomic reference type;

  3. AtomicMarkableReference: atomic updates the reference type with marker bit;

The usage of these classes is basically the same. Take AtomicReference as an example to illustrate the basic usage of these classes. Here is a demo

public class AtomicReferenceDemo {



    private static AtomicReference<User> reference = new AtomicReference<>();



    public static void main(String[] args) {

        User user1 = new User("a", 1);

        reference.set(user1);

        User user2 = new User("b",2);

        User user = reference.getAndSet(user2);

        System.out.println(user);

        System.out.println(reference.get());

    }



    static class User {

        private String userName;

        private int age;



        public User(String userName, int age) {

            this.userName = userName;

            this.age = age;

        }



        @Override

        public String toString() {

            return "User{" +

                    "userName='" + userName + '\'' +

                    ", age=" + age +

                    '}';

        }

    }

} 

Output results

User{userName='a', age=1}

User{userName='b', age=2} 

First, the object User1 is encapsulated by AtomicReference, then the getAndSet method is called. From the result, we can see that this method will update the user object referenced by the atom, and turn it into User{userName='b', age=2}, returning the original user object User{userName='a', age=1}.

[](

)Atomic update field type

If you need to update a field of an object and ensure thread safety in the case of multithreading, atomic also provides corresponding atomic operation classes:

  1. AtomicIntegeFieldUpdater: atomic update integer field class;

  2. AtomicLongFieldUpdater: atomic long field class;

  3. AtomicStampedReference: atomic update reference type with version number. The reason why the version number is added when updating is to solve the ABA problem of CAS;

To update a field with atoms requires two steps:

  1. Atomic update field classes are abstract classes. You can only create an updater through the static method newUpdater, and you need to set the classes and properties you want to update;

  2. The attributes of the update class must be decorated with public volatile;

The methods provided by these classes are basically the same. Take AtomicIntegerFieldUpdater as an example to see the specific use:

public class AtomicDemo {



    private static AtomicIntegerFieldUpdater updater = AtomicIntegerFieldUpdater.newUpdater(User.class,"age");





> **This article has been[CodeChina Open source project: [first tier big factory] Java Analysis of interview questions+Core summary learning notes+Real project practice+Latest explanation Video]](https://codechina.csdn.net/m0_60958482/java-p7), self-taught programming route and a series of technical articles are continuously updated**

Posted by Xianoth on Sat, 20 Nov 2021 03:01:09 -0800