1 13 14 package EDU.oswego.cs.dl.util.concurrent; 15 16 21 22 public class SynchronizedDouble extends SynchronizedVariable implements Comparable , Cloneable { 23 24 protected double value_; 25 26 30 public SynchronizedDouble(double initialValue) { 31 super(); 32 value_ = initialValue; 33 } 34 35 39 public SynchronizedDouble(double initialValue, Object lock) { 40 super(lock); 41 value_ = initialValue; 42 } 43 44 47 public final double get() { synchronized(lock_) { return value_; } } 48 49 53 54 public double set(double newValue) { 55 synchronized (lock_) { 56 double old = value_; 57 value_ = newValue; 58 return old; 59 } 60 } 61 62 66 public boolean commit(double assumedValue, double newValue) { 67 synchronized(lock_) { 68 boolean success = (assumedValue == value_); 69 if (success) value_ = newValue; 70 return success; 71 } 72 } 73 74 75 84 85 public double swap(SynchronizedDouble other) { 86 if (other == this) return get(); 87 SynchronizedDouble fst = this; 88 SynchronizedDouble snd = other; 89 if (System.identityHashCode(fst) > System.identityHashCode(snd)) { 90 fst = other; 91 snd = this; 92 } 93 synchronized(fst.lock_) { 94 synchronized(snd.lock_) { 95 fst.set(snd.set(fst.get())); 96 return get(); 97 } 98 } 99 } 100 101 102 106 public double add(double amount) { 107 synchronized (lock_) { 108 return value_ += amount; 109 } 110 } 111 112 116 public double subtract(double amount) { 117 synchronized (lock_) { 118 return value_ -= amount; 119 } 120 } 121 122 126 public synchronized double multiply(double factor) { 127 synchronized (lock_) { 128 return value_ *= factor; 129 } 130 } 131 132 136 public double divide(double factor) { 137 synchronized (lock_) { 138 return value_ /= factor; 139 } 140 } 141 142 public int compareTo(double other) { 143 double val = get(); 144 return (val < other)? -1 : (val == other)? 0 : 1; 145 } 146 147 public int compareTo(SynchronizedDouble other) { 148 return compareTo(other.get()); 149 } 150 151 public int compareTo(Object other) { 152 return compareTo((SynchronizedDouble)other); 153 } 154 155 public boolean equals(Object other) { 156 if (other != null && 157 other instanceof SynchronizedDouble) 158 return get() == ((SynchronizedDouble)other).get(); 159 else 160 return false; 161 } 162 163 public int hashCode() { long bits = Double.doubleToLongBits(get()); 165 return (int)(bits ^ (bits >> 32)); 166 } 167 168 public String toString() { return String.valueOf(get()); } 169 170 } 171 172 | Popular Tags |