Skip to content

Instantly share code, notes, and snippets.

@mantognini
Created November 23, 2017 16:54
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 mantognini/61af7710898f403befbd80392ca71a53 to your computer and use it in GitHub Desktop.
Save mantognini/61af7710898f403befbd80392ca71a53 to your computer and use it in GitHub Desktop.
class Lazy[T](computeValue: => T) {
@volatile private var computed = false
@volatile private var computing = false // ignore me
private var value: T = _
def get: T = {
if (!computed)
//synchronized
{
if (!computed) {
//assert(!computing)
computing = true
value = computeValue
computed = true
computing = false
}
}
value
}
object Lazy {
def apply[T](computeValue: => T) = new Lazy(computeValue)
}
object A {
def compute: Int = {
var res = 0
val t = new Thread() {
override def run(): Unit = { res = B.lazyB.get }
}
t.start()
t.join()
res
}
val lazyA = Lazy(compute)
}
object B {
def compute: Int = {
var res = 0
val t = new Thread() {
override def run(): Unit = { res = A.lazyA.get }
}
t.start()
t.join()
res
}
val lazyB = Lazy(compute)
}
object ReinteringLock extends App {
println(A.lazyA.get)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment