1 13 14 package EDU.oswego.cs.dl.util.concurrent; 15 16 21 22 public class SynchronizedBoolean extends SynchronizedVariable implements Comparable , Cloneable { 23 protected boolean value_; 24 25 29 public SynchronizedBoolean(boolean initialValue) { 30 super(); 31 value_ = initialValue; 32 } 33 34 38 public SynchronizedBoolean(boolean initialValue, Object lock) { 39 super(lock); 40 value_ = initialValue; 41 } 42 43 46 public final boolean get() { synchronized(lock_) { return value_; } } 47 48 52 53 public boolean set(boolean newValue) { 54 synchronized (lock_) { 55 boolean old = value_; 56 value_ = newValue; 57 return old; 58 } 59 } 60 61 65 public boolean commit(boolean assumedValue, boolean newValue) { 66 synchronized(lock_) { 67 boolean success = (assumedValue == value_); 68 if (success) value_ = newValue; 69 return success; 70 } 71 } 72 73 82 83 public boolean swap(SynchronizedBoolean other) { 84 if (other == this) return get(); 85 SynchronizedBoolean fst = this; 86 SynchronizedBoolean snd = other; 87 if (System.identityHashCode(fst) > System.identityHashCode(snd)) { 88 fst = other; 89 snd = this; 90 } 91 synchronized(fst.lock_) { 92 synchronized(snd.lock_) { 93 fst.set(snd.set(fst.get())); 94 return get(); 95 } 96 } 97 } 98 99 103 public boolean complement() { 104 synchronized (lock_) { 105 value_ = !value_; 106 return value_; 107 } 108 } 109 110 114 public boolean and(boolean b) { 115 synchronized (lock_) { 116 value_ = value_ & b; 117 return value_; 118 } 119 } 120 121 125 public boolean or(boolean b) { 126 synchronized (lock_) { 127 value_ = value_ | b; 128 return value_; 129 } 130 } 131 132 133 137 public boolean xor(boolean b) { 138 synchronized (lock_) { 139 value_ = value_ ^ b; 140 return value_; 141 } 142 } 143 144 145 public int compareTo(boolean other) { 146 boolean val = get(); 147 return (val == other)? 0 : (val)? 1 : -1; 148 } 149 150 public int compareTo(SynchronizedBoolean other) { 151 return compareTo(other.get()); 152 } 153 154 public int compareTo(Object other) { 155 return compareTo((SynchronizedBoolean)other); 156 } 157 158 159 public boolean equals(Object other) { 160 if (other != null && 161 other instanceof SynchronizedBoolean) 162 return get() == ((SynchronizedBoolean)other).get(); 163 else 164 return false; 165 } 166 167 public int hashCode() { 168 boolean b = get(); 169 return (b)? 3412688 : 8319343; } 171 172 public String toString() { return String.valueOf(get()); } 173 174 } 175 176 | Popular Tags |