Skip to content

Instantly share code, notes, and snippets.

@Timshel
Forked from piotrga/gist:1986175
Created July 12, 2013 11:50
Show Gist options
  • Save Timshel/5983890 to your computer and use it in GitHub Desktop.
Save Timshel/5983890 to your computer and use it in GitHub Desktop.
Atomic Sugar
import annotation.tailrec
import java.util.concurrent.atomic.AtomicReference
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)
}
}
object Atomic {
def apply[T]( obj : T ) = new Atomic(new AtomicReference(obj))
implicit def toAtomic[T]( ref : AtomicReference[T]) : Atomic[T] = new Atomic(ref)
implicit def delegateToAtomicReference[T]( a: Atomic[T] ) = a.atomic
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment