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 /**
39  * An {@code AtomicStampedReference} maintains an object reference
40  * along with an integer "stamp", that can be updated atomically.
41  *
42  * <p>Implementation note: This implementation maintains stamped
43  * references by creating internal objects representing "boxed"
44  * [reference, integer] pairs.
45  *
46  * @since 1.5
47  * @author Doug Lea
48  * @param <V> The type of object referred to by this reference
49  */
50 public class AtomicStampedReference<V> {
51 
52     private static class Pair<T> {
53         final T reference;
54         final int stamp;
Pair(T reference, int stamp)55         private Pair(T reference, int stamp) {
56             this.reference = reference;
57             this.stamp = stamp;
58         }
of(T reference, int stamp)59         static <T> Pair<T> of(T reference, int stamp) {
60             return new Pair<T>(reference, stamp);
61         }
62     }
63 
64     private volatile Pair<V> pair;
65 
66     /**
67      * Creates a new {@code AtomicStampedReference} with the given
68      * initial values.
69      *
70      * @param initialRef the initial reference
71      * @param initialStamp the initial stamp
72      */
AtomicStampedReference(V initialRef, int initialStamp)73     public AtomicStampedReference(V initialRef, int initialStamp) {
74         pair = Pair.of(initialRef, initialStamp);
75     }
76 
77     /**
78      * Returns the current value of the reference.
79      *
80      * @return the current value of the reference
81      */
getReference()82     public V getReference() {
83         return pair.reference;
84     }
85 
86     /**
87      * Returns the current value of the stamp.
88      *
89      * @return the current value of the stamp
90      */
getStamp()91     public int getStamp() {
92         return pair.stamp;
93     }
94 
95     /**
96      * Returns the current values of both the reference and the stamp.
97      * Typical usage is {@code int[1] holder; ref = v.get(holder); }.
98      *
99      * @param stampHolder an array of size of at least one.  On return,
100      * {@code stampHolder[0]} will hold the value of the stamp.
101      * @return the current value of the reference
102      */
get(int[] stampHolder)103     public V get(int[] stampHolder) {
104         Pair<V> pair = this.pair;
105         stampHolder[0] = pair.stamp;
106         return pair.reference;
107     }
108 
109     /**
110      * Atomically sets the value of both the reference and stamp
111      * to the given update values if the
112      * current reference is {@code ==} to the expected reference
113      * and the current stamp is equal to the expected stamp.
114      *
115      * <p><a href="package-summary.html#weakCompareAndSet">May fail
116      * spuriously and does not provide ordering guarantees</a>, so is
117      * only rarely an appropriate alternative to {@code compareAndSet}.
118      *
119      * @param expectedReference the expected value of the reference
120      * @param newReference the new value for the reference
121      * @param expectedStamp the expected value of the stamp
122      * @param newStamp the new value for the stamp
123      * @return {@code true} if successful
124      */
weakCompareAndSet(V expectedReference, V newReference, int expectedStamp, int newStamp)125     public boolean weakCompareAndSet(V   expectedReference,
126                                      V   newReference,
127                                      int expectedStamp,
128                                      int newStamp) {
129         return compareAndSet(expectedReference, newReference,
130                              expectedStamp, newStamp);
131     }
132 
133     /**
134      * Atomically sets the value of both the reference and stamp
135      * to the given update values if the
136      * current reference is {@code ==} to the expected reference
137      * and the current stamp is equal to the expected stamp.
138      *
139      * @param expectedReference the expected value of the reference
140      * @param newReference the new value for the reference
141      * @param expectedStamp the expected value of the stamp
142      * @param newStamp the new value for the stamp
143      * @return {@code true} if successful
144      */
compareAndSet(V expectedReference, V newReference, int expectedStamp, int newStamp)145     public boolean compareAndSet(V   expectedReference,
146                                  V   newReference,
147                                  int expectedStamp,
148                                  int newStamp) {
149         Pair<V> current = pair;
150         return
151             expectedReference == current.reference &&
152             expectedStamp == current.stamp &&
153             ((newReference == current.reference &&
154               newStamp == current.stamp) ||
155              casPair(current, Pair.of(newReference, newStamp)));
156     }
157 
158     /**
159      * Unconditionally sets the value of both the reference and stamp.
160      *
161      * @param newReference the new value for the reference
162      * @param newStamp the new value for the stamp
163      */
set(V newReference, int newStamp)164     public void set(V newReference, int newStamp) {
165         Pair<V> current = pair;
166         if (newReference != current.reference || newStamp != current.stamp)
167             this.pair = Pair.of(newReference, newStamp);
168     }
169 
170     /**
171      * Atomically sets the value of the stamp to the given update value
172      * if the current reference is {@code ==} to the expected
173      * reference.  Any given invocation of this operation may fail
174      * (return {@code false}) spuriously, but repeated invocation
175      * when the current value holds the expected value and no other
176      * thread is also attempting to set the value will eventually
177      * succeed.
178      *
179      * @param expectedReference the expected value of the reference
180      * @param newStamp the new value for the stamp
181      * @return {@code true} if successful
182      */
attemptStamp(V expectedReference, int newStamp)183     public boolean attemptStamp(V expectedReference, int newStamp) {
184         Pair<V> current = pair;
185         return
186             expectedReference == current.reference &&
187             (newStamp == current.stamp ||
188              casPair(current, Pair.of(expectedReference, newStamp)));
189     }
190 
191     // Unsafe mechanics
192 
193     private static final sun.misc.Unsafe U = sun.misc.Unsafe.getUnsafe();
194     private static final long PAIR;
195     static {
196         try {
197             PAIR = U.objectFieldOffset
198                 (AtomicStampedReference.class.getDeclaredField("pair"));
199         } catch (ReflectiveOperationException e) {
200             throw new Error(e);
201         }
202     }
203 
casPair(Pair<V> cmp, Pair<V> val)204     private boolean casPair(Pair<V> cmp, Pair<V> val) {
205         return U.compareAndSwapObject(this, PAIR, cmp, val);
206     }
207 }
208