asterix.atomic.AtomicAny.scala Maven / Gradle / Ivy
The newest version!
/*
* Copyright (c) 2014-2015 by its authors. Some rights reserved.
* See the project's home at: https://github.com/monifu/asterix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package asterix.atomic
final class AtomicAny[T] private[atomic] (initialValue: T) extends Atomic[T] {
private[this] var ref = initialValue
def getAndSet(update: T): T = {
val current = ref
ref = update
current
}
def compareAndSet(expect: T, update: T): Boolean = {
if (ref == expect) {
ref = update
true
}
else
false
}
def set(update: T): Unit = {
ref = update
}
def get: T = ref
def transformAndExtract[U](cb: (T) => (U, T)): U = {
val (r, update) = cb(ref)
ref = update
r
}
def transformAndGet(cb: (T) => T): T = {
val update = cb(ref)
ref = update
update
}
def getAndTransform(cb: (T) => T): T = {
val current = ref
ref = cb(ref)
current
}
def transform(cb: (T) => T): Unit = {
ref = cb(ref)
}
@inline
def update(value: T): Unit = set(value)
@inline
def `:=`(value: T): Unit = set(value)
@inline
def lazySet(update: T): Unit = set(update)
}
object AtomicAny {
def apply[T](initialValue: T): AtomicAny[T] =
new AtomicAny(initialValue)
}