Skip to content

Instantly share code, notes, and snippets.

@borkdude
Created March 23, 2016 16:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save borkdude/2772ccead843832c0956 to your computer and use it in GitHub Desktop.
Save borkdude/2772ccead843832c0956 to your computer and use it in GitHub Desktop.
Atoms in Scala
import java.util.concurrent.atomic.AtomicReference
import scala.annotation.tailrec
class Atom[T <: AnyRef](initialValue: T) {
private val value = new AtomicReference[T](initialValue)
def swap(fun: T => T) {
@tailrec def update(expect: T): Unit =
if ( !value.compareAndSet(expect, fun(expect)) ) update(value.get)
update(value.get)
}
def apply() = value.get
}
class MapAtom[K,V](initialValue: Map[K,V]) extends Atom(initialValue) {
def update(key: K, value: V) = this.swap(_.updated(key,value))
}
object Main extends App {
val myAtom = new Atom(Map('foo -> "fooval"))
myAtom.swap( (old) => old.updated('foo, "foonewval"))
myAtom.swap(_.updated('foo, "foonewval"))
println(myAtom())
val myMapAtom = new MapAtom[Symbol,String](Map('foo -> "fooval"))
myMapAtom.update('foo,"foonewval")
println(myMapAtom())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment