1 13 14 package EDU.oswego.cs.dl.util.concurrent; 15 import java.io.*; 16 17 23 24 public class SynchronizedRef extends SynchronizedVariable { 25 26 protected Object value_; 27 28 32 public SynchronizedRef(Object initialValue) { 33 super(); 34 value_ = initialValue; 35 } 36 37 41 public SynchronizedRef(Object initialValue, Object lock) { 42 super(lock); 43 value_ = initialValue; 44 } 45 46 49 public final Object get() { synchronized(lock_) { return value_; } } 50 51 55 56 public Object set(Object newValue) { 57 synchronized (lock_) { 58 Object old = value_; 59 value_ = newValue; 60 return old; 61 } 62 } 63 64 68 public boolean commit(Object assumedValue, Object newValue) { 69 synchronized(lock_) { 70 boolean success = (assumedValue == value_); 71 if (success) value_ = newValue; 72 return success; 73 } 74 } 75 76 77 86 87 public Object swap(SynchronizedRef other) { 88 if (other == this) return get(); 89 SynchronizedRef fst = this; 90 SynchronizedRef snd = other; 91 if (System.identityHashCode(fst) > System.identityHashCode(snd)) { 92 fst = other; 93 snd = this; 94 } 95 synchronized(fst.lock_) { 96 synchronized(snd.lock_) { 97 fst.set(snd.set(fst.get())); 98 return get(); 99 } 100 } 101 } 102 103 104 } 105 | Popular Tags |