title: Does the following lock-free code exhibit a race-condition?
body: <p>Within the <a href="https://github.com/kubernetes/kubernetes/blob/master/pkg/storage/util.go#L148" rel="nofollow noreferrer">Kubernetes Go repo on Github.com</a>,</p>
  
  <p>There is a lock-free implementation of a HighWaterMark data-structure.  This code relies on atomic operations to achieve thread-safe code that is free of data races.</p>
  
  <pre><code>// HighWaterMark is a thread-safe object for tracking the maximum value seen
  // for some quantity.
  type HighWaterMark int64
  
  // Update returns true if and only if 'current' is the highest value ever seen.
  func (hwm *HighWaterMark) Update(current int64) bool {
      for {
          old := atomic.LoadInt64((*int64)(hwm))
          if current &lt;= old {
              return false
          }
          if atomic.CompareAndSwapInt64((*int64)(hwm), old, current) {
              return true
          }
      }
  }
  </code></pre>
  
  <p>This code relies on the <code>atomic.LoadInt64</code> and <code>atomic.CompareAndSwapInt64</code> functions within the standard library to achieve data race free code...which I believe it does but I believe there is another problem of a race condition.</p>
  
  <p>If two competing threads (<code>goroutines</code>) are executing such code there exists an edge case where after the <code>atomic.LoadInt64</code> occurs in the first thread, the second thread could have swapped out for a higher value. But after the first thread <em>thinks</em> the <code>current</code> int64 is actually larger than the <code>old</code> int64 a swap will happen.  This swap would then effectively lower the stored value due to observing a stale <code>old</code> value.</p>