Atomic Package Usage Guide in Java

Source: Internet
Author: User
Tags cas volatile

http://ifeve.com/java-atomic/

Atomic Package Usage Guide in Java

This article starts in the concurrent network, the square takeoff

Introduction

Java provides the java.util.concurrent.atomic package from JDK1.5, allowing programmers to perform atomic operations without locking in a multithreaded environment. The bottom of the atomic variable uses the atomic instructions provided by the processor, but different CPU architectures may provide an atomic directive that may require some form of internal lock, so the method does not absolutely guarantee that the thread will not be blocked.

Atomic Package Introduction

In the atomic package, there are 12 classes, four atomic update methods, namely atomic Update primitives, Atomic update arrays, atomic update references, and atomic update fields. The classes in the atomic package are basically wrapper classes that are implemented using unsafe.

Atomic Update base Type class

To update the base type in an atomic way, the atomic package provides the following three classes:

    • Atomicboolean: Atomic Update Boolean type.
    • Atomicinteger: Atomic update integral type.
    • Atomiclong: Atomic update Long integer.

The common methods of Atomicinteger are as follows:

    • int addandget (int delta): atomically adds the input value to the value in the instance (value in Atomicinteger) and returns the result
    • Boolean compareandset (int expect, int update): If the entered value equals the expected value, the value is atomically set to the input value.
    • int getandincrement (): atomically adds 1 to the current value, note: This returns the value before the increment.
    • void Lazyset (int newvalue): Eventually set to NewValue, using Lazyset setting the value may cause other threads to read the old value for a short period of time. More information on this method can be found in the concurrent web translation of an article "How does the Atomiclong.lazyset work?" 》
    • int getandset (int newvalue): atomically sets the value to NewValue and returns the old value.

The Atomicinteger example code is as follows:

01

importjava.util.concurrent.atomic.AtomicInteger;

02

03

publicclassAtomicIntegerTest {

04

05

    staticAtomicInteger ai = newAtomicInteger(1);

06

07

    publicstatic voidmain(String[] args) {

08

        System.out.println(ai.getAndIncrement());

09

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

10

    }

11

12

}

Output

1
2
After-dinner dessert

The atomic package provides three basic types of atomic updates, but the basic types of Java are also char,float and double. So the question comes, how does the atom update other basic types? Atomic package of the class is basically the use of unsafe implementation, let us look at the source of unsafe, found that unsafe only provides three CAs methods, Compareandswapobject,compareandswapint and Compareandswaplong, and then look at Atomicboolean source code, found that it is first to convert the Boolean to integer type, and then use Compareandswapint for CAs, so the atomic update double can also be implemented with similar ideas.

Atomic Update Array Class

by atomically updating an element in an array, the atomic package provides the following three classes:

    • Atomicintegerarray: Atoms update elements in an integer array.
    • Atomiclongarray: Atoms update elements in an array of long integers.
    • Atomicreferencearray: An atom updates an element in an array of reference types.

The Atomicintegerarray class primarily provides an atomic way to update an integer type in an array, which is commonly used in the following ways

    • int addandget (int i, int delta): atomically adds the input value to the element of index i in the array.
    • Boolean compareandset (int i, int expect, int update): atomically sets the element of the array position I to the update value if the current value equals the expected value.

The instance code is as follows:

01

publicclassAtomicIntegerArrayTest {

02

03

    staticint[] value = new int[] { 1, 2};

04

05

    staticAtomicIntegerArray ai = newAtomicIntegerArray(value);

06

07

    publicstatic voidmain(String[] args) {

08

        ai.getAndSet(0, 3);

09

        System.out.println(ai.get(0));

10

                System.out.println(value[0]);

11

    }

12

13

}

Output

3
1

The Atomicintegerarray class needs to be aware that the array value is passed through the construction method, and then Atomicintegerarray copies the current array, so when Atomicintegerarray modifies the inner array elements, Does not affect the array that is passed in.

Atomic Update Reference type

Atomic Update primitive type Atomicinteger, only one variable can be updated, if you want to update more than one variable, you need to use this atom to update the class provided by the reference type. The atomic package provides the following three classes:

    • Atomicreference: Atomic update reference type.
    • Atomicreferencefieldupdater: Atom updates a field in a reference type.
    • Atomicmarkablereference: Atom updates A reference type with a tag bit. Can atomically update the token bit and reference type of a Boolean type. Construction method is atomicmarkablereference (V initialref, Boolean Initialmark)

The example code for Atomicreference is as follows:

01

publicclassAtomicReferenceTest {

02

03

    publicstatic AtomicReference<user> atomicUserRef = newAtomicReference</user><user>();

04

05

    publicstatic voidmain(String[] args) {

06

        User user = newUser("conan", 15);

07

        atomicUserRef.set(user);

08

        User updateUser = newUser("Shinichi", 17);

09

        atomicUserRef.compareAndSet(user, updateUser);

10

        System.out.println(atomicUserRef.get().getName());

11

        System.out.println(atomicUserRef.get().getOld());

12

    }

13

14

    staticclassUser {

15

        privateString name;

16

        privateintold;

17

18

        publicUser(String name, intold) {

19

            this.name = name;

20

            this.old = old;

21

        }

22

23

        publicString getName() {

24

            returnname;

25

        }

26

27

        publicintgetOld() {

28

            returnold;

29

        }

30

    }

31

}

Output

Shinichi
17
Atom Update Field Class

If we only need a field in a class, then we need to use the Atom Update field class, the atomic package provides the following three classes:

    • Atomicintegerfieldupdater: An update to the field of an atomic update integer.
    • Atomiclongfieldupdater: atomically updates the updater of the long field.
    • Atomicstampedreference: Atom updates A reference type with a version number. This class associates an integer value with a reference and can be used for atomic data and version numbers of data, which resolves an ABA problem that may occur when atomic updates are used with CAs.

Atomic Update field classes are abstract classes that must be created with the static method Newupdater each time you use it. The field of the atomic update class must use the public volatile modifier. The example code for Atomicintegerfieldupdater is as follows:

01

publicclassAtomicIntegerFieldUpdaterTest {

02

03

    privatestaticAtomicIntegerFieldUpdater<User> a = AtomicIntegerFieldUpdater

04

            .newUpdater(User.class, "old");

05

06

    publicstatic voidmain(String[] args) {

07

        User conan = newUser("conan", 10);

08

        System.out.println(a.getAndIncrement(conan));

09

        System.out.println(a.get(conan));

10

    }

11

12

    publicstatic classUser {

13

        privateString name;

14

        publicvolatile intold;

15

16

        publicUser(String name, intold) {

17

            this.name = name;

18

            this.old = old;

19

        }

20

21

        publicString getName() {

22

            returnname;

23

        }

24

25

        publicintgetOld() {

26

            returnold;

27

        }

28

    }

29

}

Output

10
11

Atomic Package Usage Guide in Java

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.