title: Greater-than compare-and-swap
body: <p>As the title suggests, I'm looking for a compare-and-swap implementation, but with greater-than comparison:</p>
  
  <pre><code>if(newValue &gt; oldValue) {
      oldValue = newValue;
  }
  </code></pre>
  
  <p>where <code>oldValue</code> is some global shared state and <code>newValue</code> is private to each thread, without doing this:</p>
  
  <pre><code>synchronized(locker) {
      if(newValue &gt; oldValue) {
          oldValue = newValue;
      }       
  }
  </code></pre>
  
  <p>because I want a non-blocking solution. From studying source codes of other non-blocking operations, I've come up with this (assuming the values are integers):</p>
  
  <pre><code>AtomicInteger oldValue; // shared global variable
  
  ...
  
  public boolean GreaterThanCAS(int newValue) {
  
      while(true) {
          int local = oldValue;
          if(local == oldValue) {
              if(newValue &gt; local) {
                   if(oldValue.compareAndSet(local, newValue) {
                       return true;  // swap successful
                   } // else keep looping
              } else {
                   return false; // swap failed
              }
          } // else keep looping
      }
  }
  </code></pre>
  
  <p>when <code>// else keep looping</code> happens, it means that another thread has changed the <code>oldValue</code> in the meantime and so I need to loop and try again.</p>
  
  <p>Is this implementation correct (thread-safe)?</p>