1 7 8 package java.util.concurrent.atomic; 9 10 22 public class AtomicStampedReference<V> { 23 24 private static class ReferenceIntegerPair<T> { 25 private final T reference; 26 private final int integer; 27 ReferenceIntegerPair(T r, int i) { 28 reference = r; integer = i; 29 } 30 } 31 32 private final AtomicReference <ReferenceIntegerPair<V>> atomicRef; 33 34 41 public AtomicStampedReference(V initialRef, int initialStamp) { 42 atomicRef = new AtomicReference <ReferenceIntegerPair<V>> 43 (new ReferenceIntegerPair<V>(initialRef, initialStamp)); 44 } 45 46 51 public V getReference() { 52 return atomicRef.get().reference; 53 } 54 55 60 public int getStamp() { 61 return atomicRef.get().integer; 62 } 63 64 72 public V get(int[] stampHolder) { 73 ReferenceIntegerPair<V> p = atomicRef.get(); 74 stampHolder[0] = p.integer; 75 return p.reference; 76 } 77 78 94 public boolean weakCompareAndSet(V expectedReference, 95 V newReference, 96 int expectedStamp, 97 int newStamp) { 98 ReferenceIntegerPair current = atomicRef.get(); 99 return expectedReference == current.reference && 100 expectedStamp == current.integer && 101 ((newReference == current.reference && 102 newStamp == current.integer) || 103 atomicRef.weakCompareAndSet(current, 104 new ReferenceIntegerPair<V>(newReference, 105 newStamp))); 106 } 107 108 120 public boolean compareAndSet(V expectedReference, 121 V newReference, 122 int expectedStamp, 123 int newStamp) { 124 ReferenceIntegerPair current = atomicRef.get(); 125 return expectedReference == current.reference && 126 expectedStamp == current.integer && 127 ((newReference == current.reference && 128 newStamp == current.integer) || 129 atomicRef.compareAndSet(current, 130 new ReferenceIntegerPair<V>(newReference, 131 newStamp))); 132 } 133 134 135 141 public void set(V newReference, int newStamp) { 142 ReferenceIntegerPair current = atomicRef.get(); 143 if (newReference != current.reference || newStamp != current.integer) 144 atomicRef.set(new ReferenceIntegerPair<V>(newReference, newStamp)); 145 } 146 147 160 public boolean attemptStamp(V expectedReference, int newStamp) { 161 ReferenceIntegerPair current = atomicRef.get(); 162 return expectedReference == current.reference && 163 (newStamp == current.integer || 164 atomicRef.compareAndSet(current, 165 new ReferenceIntegerPair<V>(expectedReference, 166 newStamp))); 167 } 168 } 169 | Popular Tags |