1 13 14 package EDU.oswego.cs.dl.util.concurrent; 15 16 21 22 public class SynchronizedChar extends SynchronizedVariable implements Comparable , Cloneable { 23 24 protected char value_; 25 26 30 public SynchronizedChar(char initialValue) { 31 super(); 32 value_ = initialValue; 33 } 34 35 39 public SynchronizedChar(char initialValue, Object lock) { 40 super(lock); 41 value_ = initialValue; 42 } 43 44 47 public final char get() { synchronized(lock_) { return value_; } } 48 49 53 54 public char set(char newValue) { 55 synchronized (lock_) { 56 char old = value_; 57 value_ = newValue; 58 return old; 59 } 60 } 61 62 66 public boolean commit(char assumedValue, char 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 char swap(SynchronizedChar other) { 86 if (other == this) return get(); 87 SynchronizedChar fst = this; 88 SynchronizedChar 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 105 public char add(char amount) { 106 synchronized (lock_) { 107 return value_ += amount; 108 } 109 } 110 111 115 public char subtract(char amount) { 116 synchronized (lock_) { 117 return value_ -= amount; 118 } 119 } 120 121 125 public synchronized char multiply(char factor) { 126 synchronized (lock_) { 127 return value_ *= factor; 128 } 129 } 130 131 135 public char divide(char factor) { 136 synchronized (lock_) { 137 return value_ /= factor; 138 } 139 } 140 141 public int compareTo(char other) { 142 char val = get(); 143 return (val < other)? -1 : (val == other)? 0 : 1; 144 } 145 146 public int compareTo(SynchronizedChar other) { 147 return compareTo(other.get()); 148 } 149 150 public int compareTo(Object other) { 151 return compareTo((SynchronizedChar)other); 152 } 153 154 public boolean equals(Object other) { 155 if (other != null && 156 other instanceof SynchronizedChar) 157 return get() == ((SynchronizedChar)other).get(); 158 else 159 return false; 160 } 161 162 public int hashCode() { return (int)(get()); 164 } 165 166 public String toString() { return String.valueOf(get()); } 167 168 } 169 170 | Popular Tags |