Created
March 6, 2012 13:07
-
-
Save piotrga/1986175 to your computer and use it in GitHub Desktop.
Atomic Sugar
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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