Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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