Skip to content

Instantly share code, notes, and snippets.

@piotrga
Created March 6, 2012 13:07
Show Gist options
  • Save piotrga/1986175 to your computer and use it in GitHub Desktop.
Save piotrga/1986175 to your computer and use it in GitHub Desktop.
Atomic Sugar
import annotation.tailrec
import java.util.concurrent.atomic.AtomicReference
object Atomic {
def apply[T]( obj : T) = new Atomic(new AtomicReference(obj))
implicit def toAtomic[T]( ref : AtomicReference[T]) : Atomic[T] = new Atomic(ref)
}
class Atomic[T](val atomic : AtomicReference[T]) {
@tailrec
final def update(f: T => T) : T = {
val oldValue = atomic.get()
val newValue = f(oldValue)
if (atomic.compareAndSet(oldValue, newValue)) newValue else update(f)
}
def get() = atomic.get()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment