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