Skip to content

Instantly share code, notes, and snippets.

@martintrojer
Last active December 18, 2015 16:49
Show Gist options
  • Save martintrojer/5814105 to your computer and use it in GitHub Desktop.
Save martintrojer/5814105 to your computer and use it in GitHub Desktop.
Atom
import java.util.concurrent.atomic.AtomicReference
class Atom[T](private val state: AtomicReference[T]) {
def get = state.get()
def swap(f: T => T): T = {
val v = state.get()
val newv = f(v)
if (state.compareAndSet(v, newv)) newv else swap(f)
}
def reset(nv: T) = state.set(nv)
override def toString() = get.toString
override def equals(that: Any) = that match {
case that: Atom[T] => get == that.get
case _ => false
}
object Atom {
def apply[T](state: T) = new Atom[T](new AtomicReference[T](state))
}
scala> val a = Atom[Int](1)
a: frins.Atom[Int] = 1
scala> a.swap(_ + 1)
res0: Int = 2
scala> a.get
res1: Int = 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment