Atomic Package Usage Guide in Java

Source: Internet
Author: User
Tags volatile

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.
    • int getandset (int newvalue): atomically sets the value to NewValue and returns the old value.

Atomicinteger's Demo:

Import Java.util.concurrent.atomic.AtomicInteger;  Public class Main {    static Integer a=3;     Static New Atomicinteger (a);      Public Static void Main (string[] args) {        System.out.println (ai.getandincrement ());        System.out.println (Ai.get ());        System.out.println (a);    }}
343
View Code

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.

Code:

ImportJava.util.concurrent.atomic.AtomicIntegerArray; Public classMain {Static int[] Value =New int[] {1, 2 }; StaticAtomicintegerarray ai =NewAtomicintegerarray (value);  Public Static voidMain (string[] args) {Ai.getandset (0, 3); System.out.println (Ai.get (0)); System.out.println (value[0]); System.out.println (Ai.get (1)); Ai.getandset (1,5); System.out.println (Ai.get (1)); }}
3125
View Code

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)

Code:

Importjava.util.concurrent.atomic.AtomicReference; Public classMain { Public StaticAtomicreference<user> Atomicuserref =NewAtomicreference<user>();  Public Static voidMain (string[] args) {User User=NewUser ("Conan", 15);        Atomicuserref.set (user); User UpdateUser=NewUser ("Shinichi", 17);        Atomicuserref.compareandset (user, updateUser);        System.out.println (Atomicuserref.get (). GetName ());        System.out.println (Atomicuserref.get (). Getold ());        System.out.println (User.getname ());    System.out.println (User.getold ()); }    Static classUser {PrivateString name; Private intOld ;  PublicUser (String name,intOld ) {             This. Name =name;  This. Old =Old ; }         PublicString GetName () {returnname; }         Public intGetold () {returnOld ; }    }}
ShinichiConan15
View Code

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.

Code:

ImportJava.util.concurrent.atomic.AtomicIntegerFieldUpdater; Public classMain {Private StaticAtomicintegerfieldupdater<user> A =atomicintegerfieldupdater. Newupdater (User.class, "old");  Public Static voidMain (string[] args) {User Conan=NewUser ("Conan", 10);        System.out.println (A.getandincrement (Conan));        System.out.println (A.get (Conan));    System.out.println (Conan.getold ()); }     Public Static classUser {PrivateString name;  Public volatile intOld ;  PublicUser (String name,intOld ) {             This. Name =name;  This. Old =Old ; }         PublicString GetName () {returnname; }         Public intGetold () {returnOld ; }    }}
101111
View Code

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

http://blog.csdn.net/zhangerqing/article/details/43057799

Atomic Package Usage Guide in Java

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.