Skip to content

Instantly share code, notes, and snippets.

@klaeufer
Last active December 16, 2015 08:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save klaeufer/5409867 to your computer and use it in GitHub Desktop.
Save klaeufer/5409867 to your computer and use it in GitHub Desktop.
Unsafe and safe concurrent threads for experimenting in the Scala REPL
var shared = 0
val lock = new java.lang.Object
def unsafe = {
val local = shared
Thread.sleep(0)
shared = local + 1
}
def safe = {
lock.synchronized {
val local = shared
Thread.sleep(0)
shared = local + 1
}
}
def runConcurrently(block: => Unit)(howMany: Int) = {
shared = 0
val ps = Seq.fill(howMany)(new java.lang.Thread {
override def run() = block
})
ps foreach { _.start() }
ps foreach { _.join() }
shared
}
val vu = Iterator.continually(runConcurrently(unsafe)(4)) // infinite stream of results of running runUnsafe
vu take 1000 count { _ != 4 } // see how many of the first 1000 are not 4
val vs = Iterator.continually(runConcurrently(safe)(4)) // infinite stream of results of running runSafe
vs take 1000 count { _ != 4 } // see how many of the first 1000 are not 4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment