Skip to content

Instantly share code, notes, and snippets.

@klaeufer
Last active March 13, 2026 21:39
Show Gist options
  • Select an option

  • Save klaeufer/5409867 to your computer and use it in GitHub Desktop.

Select an option

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
// first paste up to here, then the experiments below
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