Created
November 23, 2017 16:54
-
-
Save mantognini/61af7710898f403befbd80392ca71a53 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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