1 /*
   2  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   3  *
   4  * This code is free software; you can redistribute it and/or modify it
   5  * under the terms of the GNU General Public License version 2 only, as
   6  * published by the Free Software Foundation.  Oracle designates this
   7  * particular file as subject to the "Classpath" exception as provided
   8  * by Oracle in the LICENSE file that accompanied this code.
   9  *
  10  * This code is distributed in the hope that it will be useful, but WITHOUT
  11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  13  * version 2 for more details (a copy is included in the LICENSE file that
  14  * accompanied this code).
  15  *
  16  * You should have received a copy of the GNU General Public License version
  17  * 2 along with this work; if not, write to the Free Software Foundation,
  18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  19  *
  20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  21  * or visit www.oracle.com if you need additional information or have any
  22  * questions.
  23  */
  24 
  25 /*
  26  * This file is available under and governed by the GNU General Public
  27  * License version 2 only, as published by the Free Software Foundation.
  28  * However, the following notice accompanied the original version of this
  29  * file:
  30  *
  31  * Written by Doug Lea with assistance from members of JCP JSR-166
  32  * Expert Group and released to the public domain, as explained at
  33  * http://creativecommons.org/publicdomain/zero/1.0/
  34  */
  35 
  36 package java.util.concurrent.atomic;
  37 
  38 import java.lang.invoke.MethodHandles;
  39 import java.lang.invoke.VarHandle;
  40 
  41 /**
  42  * An {@code AtomicStampedReference} maintains an object reference
  43  * along with an integer "stamp", that can be updated atomically.
  44  *
  45  * <p>Implementation note: This implementation maintains stamped
  46  * references by creating internal objects representing "boxed"
  47  * [reference, integer] pairs.
  48  *
  49  * @since 1.5
  50  * @author Doug Lea
  51  * @param <V> The type of object referred to by this reference
  52  */
  53 public class AtomicStampedReference<V> {
  54 
  55     private static class Pair<T> {
  56         final T reference;
  57         final int stamp;
  58         private Pair(T reference, int stamp) {
  59             this.reference = reference;
  60             this.stamp = stamp;
  61         }
  62         static <T> Pair<T> of(T reference, int stamp) {
  63             return new Pair<T>(reference, stamp);
  64         }
  65     }
  66 
  67     private volatile Pair<V> pair;
  68 
  69     /**
  70      * Creates a new {@code AtomicStampedReference} with the given
  71      * initial values.
  72      *
  73      * @param initialRef the initial reference
  74      * @param initialStamp the initial stamp
  75      */
  76     public AtomicStampedReference(V initialRef, int initialStamp) {
  77         pair = Pair.of(initialRef, initialStamp);
  78     }
  79 
  80     /**
  81      * Returns the current value of the reference.
  82      *
  83      * @return the current value of the reference
  84      */
  85     public V getReference() {
  86         return pair.reference;
  87     }
  88 
  89     /**
  90      * Returns the current value of the stamp.
  91      *
  92      * @return the current value of the stamp
  93      */
  94     public int getStamp() {
  95         return pair.stamp;
  96     }
  97 
  98     /**
  99      * Returns the current values of both the reference and the stamp.
 100      * Typical usage is {@code int[1] holder; ref = v.get(holder); }.
 101      *
 102      * @param stampHolder an array of size of at least one.  On return,
 103      * {@code stampHolder[0]} will hold the value of the stamp.
 104      * @return the current value of the reference
 105      */
 106     public V get(int[] stampHolder) {
 107         Pair<V> pair = this.pair;
 108         stampHolder[0] = pair.stamp;
 109         return pair.reference;
 110     }
 111 
 112     /**
 113      * Atomically sets the value of both the reference and stamp
 114      * to the given update values if the
 115      * current reference is {@code ==} to the expected reference
 116      * and the current stamp is equal to the expected stamp.
 117      *
 118      * <p><a href="package-summary.html#weakCompareAndSet">May fail
 119      * spuriously and does not provide ordering guarantees</a>, so is
 120      * only rarely an appropriate alternative to {@code compareAndSet}.
 121      *
 122      * @param expectedReference the expected value of the reference
 123      * @param newReference the new value for the reference
 124      * @param expectedStamp the expected value of the stamp
 125      * @param newStamp the new value for the stamp
 126      * @return {@code true} if successful
 127      */
 128     public boolean weakCompareAndSet(V   expectedReference,
 129                                      V   newReference,
 130                                      int expectedStamp,
 131                                      int newStamp) {
 132         return compareAndSet(expectedReference, newReference,
 133                              expectedStamp, newStamp);
 134     }
 135 
 136     /**
 137      * Atomically sets the value of both the reference and stamp
 138      * to the given update values if the
 139      * current reference is {@code ==} to the expected reference
 140      * and the current stamp is equal to the expected stamp.
 141      *
 142      * @param expectedReference the expected value of the reference
 143      * @param newReference the new value for the reference
 144      * @param expectedStamp the expected value of the stamp
 145      * @param newStamp the new value for the stamp
 146      * @return {@code true} if successful
 147      */
 148     public boolean compareAndSet(V   expectedReference,
 149                                  V   newReference,
 150                                  int expectedStamp,
 151                                  int newStamp) {
 152         Pair<V> current = pair;
 153         return
 154             expectedReference == current.reference &&
 155             expectedStamp == current.stamp &&
 156             ((newReference == current.reference &&
 157               newStamp == current.stamp) ||
 158              casPair(current, Pair.of(newReference, newStamp)));
 159     }
 160 
 161     /**
 162      * Unconditionally sets the value of both the reference and stamp.
 163      *
 164      * @param newReference the new value for the reference
 165      * @param newStamp the new value for the stamp
 166      */
 167     public void set(V newReference, int newStamp) {
 168         Pair<V> current = pair;
 169         if (newReference != current.reference || newStamp != current.stamp)
 170             this.pair = Pair.of(newReference, newStamp);
 171     }
 172 
 173     /**
 174      * Atomically sets the value of the stamp to the given update value
 175      * if the current reference is {@code ==} to the expected
 176      * reference.  Any given invocation of this operation may fail
 177      * (return {@code false}) spuriously, but repeated invocation
 178      * when the current value holds the expected value and no other
 179      * thread is also attempting to set the value will eventually
 180      * succeed.
 181      *
 182      * @param expectedReference the expected value of the reference
 183      * @param newStamp the new value for the stamp
 184      * @return {@code true} if successful
 185      */
 186     public boolean attemptStamp(V expectedReference, int newStamp) {
 187         Pair<V> current = pair;
 188         return
 189             expectedReference == current.reference &&
 190             (newStamp == current.stamp ||
 191              casPair(current, Pair.of(expectedReference, newStamp)));
 192     }
 193 
 194     // VarHandle mechanics
 195     private static final VarHandle PAIR;
 196     static {
 197         try {
 198             MethodHandles.Lookup l = MethodHandles.lookup();
 199             PAIR = l.findVarHandle(AtomicStampedReference.class, "pair",
 200                                    Pair.class);
 201         } catch (ReflectiveOperationException e) {
 202             throw new ExceptionInInitializerError(e);
 203         }
 204     }
 205 
 206     private boolean casPair(Pair<V> cmp, Pair<V> val) {
 207         return PAIR.compareAndSet(this, cmp, val);
 208     }
 209 }