Created
March 23, 2016 16:57
-
-
Save borkdude/2772ccead843832c0956 to your computer and use it in GitHub Desktop.
Atoms in Scala
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 | |
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