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