Skip to content

Fix #2275: Fix deadlock in @volatile lazy vals #5447

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 15, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/docs/reference/changed/lazy-vals-spec.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ class Foo {
LazyVals.wait4Notification(this, bitmap_offset, flag, <field-id>)
case <state-3> =>
retry = false
result = $target
result = value_0
}
}
result
Expand Down
5 changes: 3 additions & 2 deletions library/src/dotty/runtime/LazyVals.scala
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ object LazyVals {
var retry = true
while (retry) {
val cur = get(t, offset)
if (STATE(cur, ord) == 1) retry = CAS(t, offset, cur, v, ord)
if (STATE(cur, ord) == 1) retry = !CAS(t, offset, cur, v, ord)
else {
// cur == 2, somebody is waiting on monitor
if (CAS(t, offset, cur, v, ord)) {
Expand All @@ -67,7 +67,8 @@ object LazyVals {
else if (state == 2) {
val monitor = getMonitor(t, ord)
monitor.synchronized {
monitor.wait()
if (STATE(get(t, offset), ord) == 2) // make sure notification did not happen yet.
monitor.wait()
}
}
else retry = false
Expand Down
19 changes: 19 additions & 0 deletions tests/run/i2275.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
object Test {
var count = 0

@volatile lazy val x: Int = {
if (count < 100) {
count += 1
???
}
1
}

def main(args: Array[String]): Unit = {
def fetchLazy(): Unit = try x catch { case _: Throwable => fetchLazy() }

for (_ <- 0 until 10) {
new Thread(() => fetchLazy()).start()
}
}
}