Last active
December 18, 2015 16:49
-
-
Save martintrojer/5814105 to your computer and use it in GitHub Desktop.
Atom
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 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)) | |
} |
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
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