Java Multithreading class: Juc Atomic class: 05 Atomicintegerfieldupdater Atomic Class

Source: Internet
Author: User
Tags modifiers

Overview

Atomicintegerfieldupdater, Atomiclongfieldupdater and atomicreferencefieldupdater are similar in principle and usage to the atomic types of the 3 members of the modified class. This chapter provides an introduction to the atomic classes of basic types. The content includes:
Atomiclongfieldupdater Introduction and Function List
Atomiclongfieldupdater Example
Atomiclongfieldupdater Source Analysis (based on jdk1.7.0_40)

Reprint Please specify source: http://www.cnblogs.com/skywang12345/p/3514623.html

atomiclongfieldupdater Introduction and Function List

Atomiclongfieldupdater can be atomically updated for members of the specified class ' volatile long ' type. It is implemented based on the principle of reflection.

List of Atomiclongfieldupdater functions

A protected, no-action construction method for use by subclasses. protected Atomiclongfieldupdater ()//atomically adds the given value to the current value of the field of the given object managed by this updater. Long Addandget (T obj, long delta)//If the current value = = expected value, the field of the given object managed by this updater is atomically set to the given update value. Abstract Boolean compareandset (T obj, long expect, long update)//atomically subtract 1 from the current value of the given object field managed by this updater. Long Decrementandget (T obj)//Gets the current value maintained in the field of the given object managed by this updater. Abstract long get (T obj)//atomically adds the given value to the current value of the field of the given object managed by this updater. Long Getandadd (T obj, long delta)//atomically converts the current value of the given object field managed by this updater by 1. Long getanddecrement (T obj)//atomically adds 1 to the current value of the given object field managed by this updater. Long getandincrement (T obj)//The field of the given object managed by this updater is atomically set to the given value, and the old value is returned. Long Getandset (T obj, long newvalue)//atomically adds 1 to the current value of the given object field managed by this updater. Long Incrementandget (T obj)//Finally sets the field of the given object managed by this updater to the given update value. abstract void Lazyset (T obj, long newvalue)//Creates and returns an updater with the given field for the object. Static <U> atomiclongfieldupdater<u> newupdater (class<u> tclass, String fieldName)// Sets the field of the given object managed by this updater to the given update value. abstract void Set (T obj, long newvalue)//If the current value = = expected value, the field of the given object managed by this updater is atomically set to the given update value. Abstract Boolean weakcompareandset (T obj, Long expect, long update) 

Atomiclongfieldupdater Example
Longtest.java Source Import Java.util.concurrent.atomic.atomiclongfieldupdater;public class Longfieldtest {        public static void Main (string[] args) {        //Gets the person's class object        class CLS = Person.class;         New Atomiclongfieldupdater object, pass parameter is "class object" and "long type corresponding name in class"        atomiclongfieldupdater Matolong = Atomiclongfieldupdater.newupdater (CLS, "id");        person person = new person (12345678L);        Compare the ID property of person, set to 1000 if the value of ID is 12345678L.        Matolong.compareandset (person, 12345678L, +);        System.out.println ("id=" +person.getid ());}    } Class Person {    volatile long ID;    Public person (long ID) {        this.id = ID;    }    public void SetId (long id) {        this.id = ID;    }    Public long GetId () {        return ID;    }}

Operation result :

id=1000

Atomiclongfieldupdater Source Analysis (based on jdk1.7.0_40)

Atomiclongfieldupdater Full Source

/*
* ORACLE proprietary/confidential. Use are subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/

/*
*
*
*
*
*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/publicdomain/zero/1.0/
*/

Package java.util.concurrent.atomic;
Import java.lang.reflect.*;
Import Sun.misc.Unsafe;
Import sun.reflect.CallerSensitive;
Import sun.reflect.Reflection;

/**
* A reflection-based utility that enables atomic updates to
* Designated {@code volatile} reference fields of designated
* classes. This is the designed for use in atomic data structures
* in which several reference fields of the same node is
* Independently subject to atomic updates. For example, a tree node
* Might be declared as
*
* <pre> {@code
* Class Node {
* Private volatile Node left, right;
*
* Private static final Atomicreferencefieldupdater<node, node> leftupdater =
* Atomicreferencefieldupdater.newupdater (Node.class, Node.class, "left");
* private static Atomicreferencefieldupdater<node, node> Rightupdater =
* Atomicreferencefieldupdater.newupdater (Node.class, Node.class, "right");
*
* Node GetLeft () {return left;}
* Boolean Compareandsetleft (node expect, node update) {
* Return Leftupdater.compareandset (this, expect, update);
* }
*//... on
*}}</pre>
*
* <p>note that the guarantees of the {@code Compareandset}
* Method in this class is weaker than in other atomic classes.
* Because This class cannot ensure, all uses of the field
* is appropriate for purposes of atomic access, it can
* Guarantee atomicity only with respect to other invocations of
* {@code Compareandset} and {@code set} on the same updater.
*
* @since 1.5
* @author Doug Lea
* @param <T> The type of the object holding the updatable field
* @param <V> The type of the field
*/
Public abstract class Atomicreferencefieldupdater<t, v> {

/**
* Creates and returns an updater for objects with the given field.
* The Class arguments is needed to Che CK that reflective types and
* Generic types match.
*
* @param tclass The class of the objects holding the FIE LD.
* @param vclass The class of the field
* @param fieldName The name of the field to be updated.
* @return T He updater
* @throws illegalargumentexception if the field is not a volatile reference type.
* @throws Runtimeexce Ption with a nested reflection-based
* exception if the class does isn't hold field or is the wrong type.
*/
@Ca Llersensitive
public static <u, w> atomicreferencefieldupdater<u,w> newupdater (class<u> tclass, Class<w> Vclass, String fieldName) {
return new atomicreferencefieldupdaterimpl<u,w> (Tclass,
Vclass,
FieldName,
Reflection.getcallerclass ());
}

/**
* Protected do-nothing constructor for use by subclasses.
*/
Protected Atomicreferencefieldupdater () {
}

/**
* atomically sets the field of the given object managed by this updater
* to the given updated value if the current value {@code = =} The
* Expected value. This method was guaranteed to being atomic with respect to
* Other calls to {@code Compareandset} and {@code set}
* Necessarily with respect to other changes in the field.
*
* @param obj A object whose field to conditionally set
* @param expect the expected value
* @param update the new value
* @return True if successful.
*/
Public abstract Boolean Compareandset (T obj, v expect, v update);

/**
* atomically sets the field of the given object managed by this updater
* to the given updated value if th E Current value {@code = =} The
* expected value. This method was guaranteed to being atomic with respect to
* Other calls to {@code Compareandset} and {@code set}
* Necessarily with respect to other changes in the field.
*
* <p>may <a href= "package-summary.html#spurious" >fail spuriously</a>
* and does not prov IDE ordering guarantees, so are only rarely a
* appropriate alternative to {@code Compareandset}.
*
* @param o BJ an object whose field to conditionally set
* @param expect the expected value
* @param update the new value
* @return True if successful.
*/
Public abstract Boolean weakcompareandset (T obj, v expect, v update);

/**
* Sets the field of the given object managed by this updater to the
* Given updated value. This operation are guaranteed to act as a volatile
* Store with respect to subsequent invocations of {@code Compareandset}.
*
* @param obj A object whose field to set
* @param newvalue The new value
*/
public abstract void Set (T obj, V newvalue);

/**
* Eventually sets the field of the given object managed by this
* Updater to the given updated value.
*
* @param obj A object whose field to set
* @param newvalue The new value
* @since 1.6
*/
public abstract void Lazyset (T obj, V newvalue);

/**
* Gets The current value held in the field of the given object managed
* By this updater.
*
* @param obj A object whose field to get
* @return The current value
*/
Public abstract V get (T obj);

/**
* atomically sets the field of the given object managed by this updater
* to the given value and returns the old value.
*
* @param obj A object whose field to get and set
* @param newvalue The new value
* @return the previous value
*/
Public V getandset (T obj, v newvalue) {
for (;;) {
V current = get (obj);
if (Compareandset (obj, current, newvalue))
return current;
}
}

Private static Final class atomicreferencefieldupdaterimpl<t,v>
Extends Atomicreferencefieldupdater<t,v> {
Private static final unsafe unsafe = unsafe.getunsafe ();
Private final long offset;
Private final class<t> Tclass;
Private final class<v> Vclass;
Private final Class Cclass;

/*
* Internal type checks within all update methods contain
* Internal inlined optimizations checking for the Common
* Cases where the class is final (in which case a simple
* getclass comparison suffices) or is of type Obje CT (in
* which case no check was needed because all objects be
* instances of Object). The Object case was handled simply by
* setting Vclass to NULL in constructor. The Targetcheck and
* UpdateCheck methods is invoked when these faster
* screenings fail.
*/

Atomicreferencefieldupdaterimpl (class<t> Tclass,
Class<v> Vclass,
String FieldName,
Class<?> caller) {
Field field = NULL;
Class fieldclass = null;
int modifiers = 0;
try {
field = Tclass.getdeclaredfield (FieldName);
modifiers = Field.getmodifiers ();
Sun.reflect.misc.ReflectUtil.ensureMemberAccess (
Caller, tclass, NULL, modifiers);
Sun.reflect.misc.ReflectUtil.checkPackageAccess (Tclass);
Fieldclass = Field.gettype ();
} catch (Exception ex) {
throw new RuntimeException (ex);
}

if (vclass! = Fieldclass)
throw new ClassCastException ();

if (! Modifier.isvolatile (modifiers))
throw new IllegalArgumentException ("must be volatile type");

This.cclass = (modifier.isprotected (modifiers) &&
Caller! = Tclass)? Caller:null;
This.tclass = Tclass;
if (Vclass = = Object.class)
This.vclass = null;
Else
This.vclass = Vclass;
offset = unsafe.objectfieldoffset (field);
}

void Targetcheck (T obj) {
if (!tclass.isinstance (obj))
throw new ClassCastException ();
if (cclass! = null)
Ensureprotectedaccess (obj);
}

void UpdateCheck (T obj, V update) {
if (!tclass.isinstance (obj) | |
(update! = NULL && Vclass! = null &&!vclass.isinstance (update)))
throw new ClassCastException ();
if (cclass! = null)
Ensureprotectedaccess (obj);
}

public boolean compareandset (T obj, v expect, v update) {
if (obj = = NULL | | Obj.getclass ()! = Tclass | | cclass = NULL | |
(update! = NULL && Vclass! = null &&
Vclass! = Update.getclass ()))
UpdateCheck (obj, update);
return Unsafe.compareandswapobject (obj, offset, expect, update);
}

public boolean weakcompareandset (T obj, v expect, v update) {
Same implementation as strong form for now
if (obj = = NULL | | Obj.getclass ()! = Tclass | | cclass = NULL | |
(update! = NULL && Vclass! = null &&
Vclass! = Update.getclass ()))
UpdateCheck (obj, update);
return Unsafe.compareandswapobject (obj, offset, expect, update);
}

public void Set (T obj, V newvalue) {
if (obj = = NULL | | Obj.getclass ()! = Tclass | | cclass = NULL | |
(NewValue! = NULL && Vclass! = null &&
Vclass! = Newvalue.getclass ()))
UpdateCheck (obj, newvalue);
Unsafe.putobjectvolatile (obj, offset, newvalue);
}

public void Lazyset (T obj, V newvalue) {
if (obj = = NULL | | Obj.getclass ()! = Tclass | | cclass = NULL | |
(NewValue! = NULL && Vclass! = null &&
Vclass! = Newvalue.getclass ()))
UpdateCheck (obj, newvalue);
Unsafe.putorderedobject (obj, offset, newvalue);
}

Public V get (T obj) {
if (obj = = NULL | | Obj.getclass ()! = Tclass | | cclass = NULL)
Targetcheck (obj);
Return (V) unsafe.getobjectvolatile (obj, offset);
}

private void Ensureprotectedaccess (T obj) {
if (cclass.isinstance (obj)) {
Return
}
throw New RuntimeException (
New Illegalaccessexception ("Class" +
Cclass.getname () +
"Can not access a protected member of class" +
Tclass.getname () +
"Using an instance of" +
Obj.getclass (). GetName ()
)
);
}
}
}

The following is an analysis of the Longfieldtest.java process.

1. Newupdater ()
The source code of Newupdater () is as follows:

public static <U> atomiclongfieldupdater<u> newupdater (class<u> tclass, String fieldName) {    class<?> caller = Reflection.getcallerclass ();    if (Atomiclong.vm_supports_long_cas)        return new casupdater<u> (Tclass, fieldName, caller);    else        return new lockedupdater<u> (Tclass, fieldName, caller);}

Description : The Role of Newupdater () is to get an object of type Atomicintegerfieldupdater.
It actually returns the Casupdater object, or the Lockedupdater object, whichever class is returned depends on whether the JVM supports a long type of CAS function. Both Casupdater and Lockedupdater are subclasses of Atomicintegerfieldupdater, and their implementations are similar. The following is explained in Casupdater.

The source code of Casupdater class is as follows:

public boolean compareandset (T obj, long expect, long update) {    if (obj = = NULL | | Obj.getclass ()! = Tclass | | cclass ! = null) Fullcheck (obj);    return Unsafe.compareandswaplong (obj, offset, expect, update);}

Description : It is actually operated through the CAS function. If the value of the long object of the class is expect, set its value to update.

Java Multithreading class: Juc Atomic class: 05 Atomicintegerfieldupdater Atomic Class

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.