github.com/timstclair/heapster@v0.20.0-alpha1/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/atomic_value.go (about)

     1  /*
     2  Copyright 2015 The Kubernetes Authors All rights reserved.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package util
    18  
    19  import (
    20  	"sync"
    21  	"sync/atomic"
    22  )
    23  
    24  // TODO(ArtfulCoder)
    25  // sync/atomic/Value was added in golang 1.4
    26  // Once support is dropped for go 1.3, this type must be deprecated in favor of sync/atomic/Value.
    27  // The functions are named Load/Store to match sync/atomic/Value function names.
    28  type AtomicValue struct {
    29  	value      interface{}
    30  	valueMutex sync.RWMutex
    31  }
    32  
    33  func (at *AtomicValue) Store(val interface{}) {
    34  	at.valueMutex.Lock()
    35  	defer at.valueMutex.Unlock()
    36  	at.value = val
    37  }
    38  
    39  func (at *AtomicValue) Load() interface{} {
    40  	at.valueMutex.RLock()
    41  	defer at.valueMutex.RUnlock()
    42  	return at.value
    43  }
    44  
    45  // HighWaterMark is a thread-safe object for tracking the maximum value seen
    46  // for some quantity.
    47  type HighWaterMark int64
    48  
    49  // Check returns true if and only if 'current' is the highest value ever seen.
    50  func (hwm *HighWaterMark) Check(current int64) bool {
    51  	for {
    52  		old := atomic.LoadInt64((*int64)(hwm))
    53  		if current <= old {
    54  			return false
    55  		}
    56  		if atomic.CompareAndSwapInt64((*int64)(hwm), old, current) {
    57  			return true
    58  		}
    59  	}
    60  }