1 7 8 package java.util.concurrent.atomic; 9 10 22 public class AtomicMarkableReference<V> { 23 24 private static class ReferenceBooleanPair<T> { 25 private final T reference; 26 private final boolean bit; 27 ReferenceBooleanPair(T r, boolean i) { 28 reference = r; bit = i; 29 } 30 } 31 32 private final AtomicReference <ReferenceBooleanPair<V>> atomicRef; 33 34 41 public AtomicMarkableReference(V initialRef, boolean initialMark) { 42 atomicRef = new AtomicReference <ReferenceBooleanPair<V>> (new ReferenceBooleanPair<V>(initialRef, initialMark)); 43 } 44 45 50 public V getReference() { 51 return atomicRef.get().reference; 52 } 53 54 59 public boolean isMarked() { 60 return atomicRef.get().bit; 61 } 62 63 71 public V get(boolean[] markHolder) { 72 ReferenceBooleanPair<V> p = atomicRef.get(); 73 markHolder[0] = p.bit; 74 return p.reference; 75 } 76 77 93 public boolean weakCompareAndSet(V expectedReference, 94 V newReference, 95 boolean expectedMark, 96 boolean newMark) { 97 ReferenceBooleanPair current = atomicRef.get(); 98 return expectedReference == current.reference && 99 expectedMark == current.bit && 100 ((newReference == current.reference && newMark == current.bit) || 101 atomicRef.weakCompareAndSet(current, 102 new ReferenceBooleanPair<V>(newReference, 103 newMark))); 104 } 105 106 118 public boolean compareAndSet(V expectedReference, 119 V newReference, 120 boolean expectedMark, 121 boolean newMark) { 122 ReferenceBooleanPair current = atomicRef.get(); 123 return expectedReference == current.reference && 124 expectedMark == current.bit && 125 ((newReference == current.reference && newMark == current.bit) || 126 atomicRef.compareAndSet(current, 127 new ReferenceBooleanPair<V>(newReference, 128 newMark))); 129 } 130 131 137 public void set(V newReference, boolean newMark) { 138 ReferenceBooleanPair current = atomicRef.get(); 139 if (newReference != current.reference || newMark != current.bit) 140 atomicRef.set(new ReferenceBooleanPair<V>(newReference, newMark)); 141 } 142 143 156 public boolean attemptMark(V expectedReference, boolean newMark) { 157 ReferenceBooleanPair current = atomicRef.get(); 158 return expectedReference == current.reference && 159 (newMark == current.bit || 160 atomicRef.compareAndSet 161 (current, new ReferenceBooleanPair<V>(expectedReference, 162 newMark))); 163 } 164 } 165 | Popular Tags |