JDK Source Code Analysis-atomicinteger

Source: Internet
Author: User
Tags cas

Atomicinteger can be seen as an atomic manipulation tool class for integer classes. Under the Java.util.concurrent.atomic package, in some use cases can replace the lock operation to improve concurrency. The following is a few things to introduce:

1. atomicity and CAs.

2.CPU bottom-level implementation principle.

3.atomic Package Introduction.

4. Source code Analysis.

  Atomicity and CAs

  Atomicity means that an operation is non-detachable, and that a whole must be completed at once or not executed.

CAS is compare and swap (compare and swap). This means that when you want to update a value, you need to check if the current value of the variable is changed, and if you change it, you cannot update it, and you can update it without changing it.

  First, the CPU compares the data that will be changed in memory with the expected value. Then, when the two values are equal, the CPU replaces the values in memory with the new values. Otherwise, do not do the operation. Finally, the CPU returns the old value. This series of operations is atomic. Although seemingly complex, they are the root of the Java 5 concurrency mechanism, which is superior to the original locking mechanism. Simply put, the meaning of CAS is "What I think the original value should be, and if it is, update the original value to a new value, otherwise do not modify, and tell me what the original value is."

  Atomic Package Introduction

  Class of widgets that support thread-safe programming for unlocking on a single variable. The classes in this package extend the concept of volatile values, fields, and array elements to classes that also provide atomic conditional update operations in the following form:

Boolean Compareandset (Expectedvalue, Updatevalue);

If this method (which differs between different classes of arguments) currently holds Expectedvalue, the variable is atomically set to updatevalue, and trueis reported on success. The classes in this package also contain methods for getting and setting values unconditionally, as well as Atomic update operation Weakcompareandsetthat describe the weaker conditions described below.

Atomic access and updated memory effects generally follow the following mutable rules:

    • get has a memory effect that reads volatile variables.
    • set has a memory effect that writes (allocates) avolatile variable.
    • In addition to allowing subsequent (but not previous) memory operations, which themselves do not impose a reordering constraint with a normal non- volatile write,Lazyset has a memory effect of writing (assigning) avolatile variable. In other usage contexts, when null (for garbage collection),Lazyset can apply a reference that is not accessed again.
    • Weakcompareandset reads and conditionally writes the variable but does not create any happen-before sort, and therefore does not provide a weakcompareandset Any guarantees related to previous or subsequent read or write operations of any variables outside the target.
    • Compareandset and all other read and update operations, such as getandincrement, have memory effects that read and write volatile variables.

The design Atom class is used primarily as a variety of building blocks for implementing non-blocking data structures and related infrastructure classes. The Compareandset method is not a regular replacement for locks. Apply it only if the object's important update is limited to a single variable. The atomic class is not a generic replacement for Java.lang.Integer and related classes. They do not define methods such as hashcode and compareTo .

  Examples of source code analysis

Atomicinteger Inheritance structure:

   -Java.lang.Object

---java.lang.Number

------Java.util.concurrent.atomic.AtomicInteger

It also implements java.io.Serializable for serialization, and then the definition and initialization of fields:

Unsafe contains many native methods that are called through JNI. Value is the atomicinteger represented by a volatile modifier to guarantee the visibility of value.

//Source codesetup to use Unsafe.compareandswapint for updates    Private Static Finalunsafe unsafe =Unsafe.getunsafe (); Private Static Final LongValueoffset; Static {        Try{Valueoffset=Unsafe.objectfieldoffset (Atomicinteger.class. Getdeclaredfield ("value")); } Catch(Exception ex) {Throw NewError (ex);} }    Private volatile intValue

Atomicinteger probably implemented about 20 public methods, here are a few representative to analyze:

The 1.get method is used to obtain the current most recent value. The final modification of the method is intended to further ensure thread safety.

    /**      * Gets the current value.     *     @return The current value     */public    Final  int  get () {        return  value;    }

The 2.set method is to update values to a new value. It is also decorated with final.

    /**      * Sets to the given value.     *     @param  newvalue The new value     */public    final void Set (int  newvalue) {        = newvalue;    }

The difference between the 3.lazySet method and the set method is that it is possible to delay the setting, that is, to set the new value at the end.

    /**      * Eventually sets to the given value.     *     @param  newvalue The new value     @since  1.6     * / Public    finalvoid lazyset (int  newvalue) {        Unsafe.putorderedint (This, Valueoffset, newvalue);    }

The 4.getAndSet method is to set the new value to the current value and then return the old value.

    /**      * atomically sets to the given value and returns the old value.     *     @param  newvalue The new value     @return the previous value      */     Public Final int getandset (int  newvalue) {        return unsafe.getandsetint (  this, Valueoffset, newvalue);    }

The 5.compareAndSet method is to first update to the new value by comparing the current value to the expected one. Returns true if the update succeeds, otherwise false.

    /*** atomically Sets the value to the given updated value * If the current value {@code= =} The expected value. *     * @paramexpect the expected value *@paramUpdate the new value *@return {@codetrue} if successful.     False return indicates that * the actual value is not equal to the expected value. */     Public Final BooleanCompareandset (intExpectintupdate) {        returnUnsafe.compareandswapint ( This, Valueoffset, expect, update); }

The 6.getAndIncrement method is an atom that adds the original value one and returns the old value. Getanddecrement similar.

    /** * atomically increments by one of the current     value.     *     @return the previous value     */public    final int getandincrement () {        return unsafe.getandaddint (This, valueoffset, 1);    } 

The 7.getAndAdd method is to add a value to the original value and return the previous value.

    /**      * atomically adds the given value to the current value.     *     @param  Delta The value to add     @return the previous value      */     Public Final int getandadd (int  delta) {        return unsafe.getandaddint (this  , Valueoffset, delta);    }

The 8.incrementAndGet method is to add the original value one after the return of the new value. Decrementandget similar.

    /** * atomically increments by one of the current     value.     *     @return The updated value     */public    final int Incrementandget () {        return unsafe.getandaddint (This, Valueoffset, 1) + 1;    }

The 9.getAndUpdate method is based on a defined operator that updates the current worth first parameter, the passed parameter as the second parameter, and returns the old value. Updateandget is the return new value. The Compareandset method is called using a spin, and only the return of true ends.

    /*** atomically updates the current value with the results of * applying the given function, returning the Previ OUs value. The * function should is side-effect-free, since it May is re-applied * When attempted updates fail due to content     Ion among threads. *     * @paramupdatefunction a side-effect-free function *@returnThe previous value *@since1.8*/     Public Final intgetandupdate (Intunaryoperator updatefunction) {intprev, Next;  Do{prev=get (); Next=Updatefunction.applyasint (prev); }  while(!Compareandset (prev, next)); returnprev; }

All of these methods are atomic operations.

  

  

  

  

JDK Source code Analysis-atomicinteger

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.