示例#1
0
  /**
   * Atomically swap values with another SynchronizedInt. Uses identityHashCode to avoid deadlock
   * when two SynchronizedInts attempt to simultaneously swap with each other. (Note: Ordering via
   * identyHashCode is not strictly guaranteed by the language specification to return unique,
   * orderable values, but in practice JVMs rely on them being unique.)
   *
   * @return the new value
   */
  public int swap(SynchronizedInt other) {
    if (other == this) {
      return get();
    }
    SynchronizedInt fst = this;
    SynchronizedInt snd = other;

    if (System.identityHashCode(fst) > System.identityHashCode(snd)) {
      fst = other;
      snd = this;
    }
    synchronized (fst.lock_) {
      synchronized (snd.lock_) {
        fst.set(snd.set(fst.get()));
        return get();
      }
    }
  }
示例#2
0
 public int compareTo(SynchronizedInt other) {
   return compareTo(other.get());
 }