当前位置: 移动技术网 > IT编程>开发语言>Java > Java concurrency之AtomicLongFieldUpdater原子类_动力节点Java学院整理

Java concurrency之AtomicLongFieldUpdater原子类_动力节点Java学院整理

2019年07月22日  | 移动技术网IT编程  | 我要评论

atomiclongfieldupdater介绍和函数列表

atomiclongfieldupdater可以对指定"类的 'volatile long'类型的成员"进行原子更新。它是基于反射原理实现的。

atomiclongfieldupdater函数列表

// 受保护的无操作构造方法,供子类使用。
protected atomiclongfieldupdater()
// 以原子方式将给定值添加到此更新器管理的给定对象的字段的当前值。
long addandget(t obj, long delta)
// 如果当前值 == 预期值,则以原子方式将此更新器所管理的给定对象的字段设置为给定的更新值。
abstract boolean compareandset(t obj, long expect, long update)
// 以原子方式将此更新器管理的给定对象字段当前值减 1。
long decrementandget(t obj)
// 获取此更新器管理的在给定对象的字段中保持的当前值。
abstract long get(t obj)
// 以原子方式将给定值添加到此更新器管理的给定对象的字段的当前值。
long getandadd(t obj, long delta)
// 以原子方式将此更新器管理的给定对象字段当前值减 1。
long getanddecrement(t obj)
// 以原子方式将此更新器管理的给定对象字段的当前值加 1。
long getandincrement(t obj)
// 将此更新器管理的给定对象的字段以原子方式设置为给定值,并返回旧值。
long getandset(t obj, long newvalue)
// 以原子方式将此更新器管理的给定对象字段当前值加 1。
long incrementandget(t obj)
// 最后将此更新器管理的给定对象的字段设置为给定更新值。
abstract void lazyset(t obj, long newvalue)
// 为对象创建并返回一个具有给定字段的更新器。
static <u> atomiclongfieldupdater<u> newupdater(class<u> tclass, string fieldname)
// 将此更新器管理的给定对象的字段设置为给定更新值。
abstract void set(t obj, long newvalue)
// 如果当前值 == 预期值,则以原子方式将此更新器所管理的给定对象的字段设置为给定的更新值。
abstract boolean weakcompareandset(t obj, long expect, long update)

atomiclongfieldupdater示例

// longtest.java的源码
import java.util.concurrent.atomic.atomiclongfieldupdater;
public class longfieldtest {
  public static void main(string[] args) {
    // 获取person的class对象
    class cls = person.class; 
    // 新建atomiclongfieldupdater对象,传递参数是“class对象”和“long类型在类中对应的名称”
    atomiclongfieldupdater matolong = atomiclongfieldupdater.newupdater(cls, "id");
    person person = new person(12345678l);
    // 比较person的"id"属性,如果id的值为12345678l,则设置为1000。
    matolong.compareandset(person, 12345678l, 1000);
    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;
  }
}

运行结果:

id=1000

atomiclongfieldupdater源码分析(基于jdk1.7.0_40)

atomiclongfieldupdater完整源码

 /*
  * oracle proprietary/confidential. use is subject to license terms.
  *
  *
  *
  *
  *
  *
  *
  *
  *
  *
  *
  *
  *
  *
  *
  *
  *
  *
  *
  *
  */
 /*
  *
  *
  *
  *
  *
  * written by doug lea with assistance from members of jcp jsr-
  * expert group and released to the public domain, as explained at
  * http://creativecommons.org/publicdomain/zero/./
  */
 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 class is designed for use in atomic data structures
  * in which several reference fields of the same node are
  * 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);
  *  }
  *  // ... and so on
  * }}</pre>
  *
  * <p>note that the guarantees of the {@code compareandset}
  * method in this class are weaker than in other atomic classes.
  * because this class cannot ensure that all uses of the field
  * are 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 .
  * @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 are needed to check that reflective types and
    * generic types match.
    *
    * @param tclass the class of the objects holding the field.
    * @param vclass the class of the field
    * @param fieldname the name of the field to be updated.
    * @return the updater
    * @throws illegalargumentexception if the field is not a volatile reference type.
    * @throws runtimeexception with a nested reflection-based
    * exception if the class does not hold field or is the wrong type.
    */
   @callersensitive
   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 is guaranteed to be atomic with respect to
   * other calls to {@code compareandset} and {@code set}, but not
   * necessarily with respect to other changes in the field.
   *
   * @param obj an 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 the current value {@code ==} the
   * expected value. this method is guaranteed to be atomic with respect to
   * other calls to {@code compareandset} and {@code set}, but not
   * necessarily with respect to other changes in the field.
   *
   * <p>may <a href="package-summary.html#spurious" rel="external nofollow" >fail spuriously</a>
   * and does not provide ordering guarantees, so is only rarely an
   * appropriate alternative to {@code compareandset}.
   *
   * @param obj 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 is guaranteed to act as a volatile
   * store with respect to subsequent invocations of {@code compareandset}.
   *
   * @param obj an 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 an 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 an 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 an 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 object (in
     * which case no check is needed because all objects are
     * instances of object). the object case is handled simply by
     * setting vclass to null in constructor. the targetcheck and
     * updatecheck methods are 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()
         )
       );
     }
   }
 }

   下面分析longfieldtest.java的流程。

1. newupdater()

newupdater()的源码如下:

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);
}

说明:newupdater()的作用是获取一个atomicintegerfieldupdater类型的对象。

它实际上返回的是casupdater对象,或者lockedupdater对象;具体返回哪一个类取决于jvm是否支持long类型的cas函数。casupdater和lockedupdater都是atomicintegerfieldupdater的子类,它们的实现类似。下面以casupdater来进行说明。 

casupdater类的源码如下:

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);
}

说明:它实际上是通过cas函数操作。如果类的long对象的值是expect,则设置它的值为update。 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网