Skip to content

Using runBlocking inside a lazy's initializer leads to multiple initializations. #1682

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

Closed
alacoste opened this issue Nov 29, 2019 · 4 comments
Assignees

Comments

@alacoste
Copy link

The following code behaves in a way that seems pretty counter-intuitive:

val myLazyVal by lazy {
  println("Running lazy initializer!")
  runBlocking {
    someSuspendFunctionForInitialization()
  }
}

fun main() = runBlocking {
  coroutineScope {
    (0 until 10).map {
      launch { myLazyVal.someOperation() }
    }
  }
}

With that code the lazy initializer can run multiple times.

Here is my understanding of why it happens, please correct me if I'm wrong:

  • We launched 10 coroutines that all try to access myLazyVal.
  • When the first coroutine gets suspended during the lazy initialization, the second one may very well be resumed on the same thread
  • I'm guessing the synchronized(lock) { ... } block used by SynchronizedLazyImpl is re-entrant and therefore lets the second coroutine re-enter the synchronized block, leading to multiple simultaneous initializations.
@qwwdfsad qwwdfsad self-assigned this Nov 29, 2019
@qwwdfsad
Copy link
Collaborator

It's not exactly that, but the idea is similar.
After #860 nested runBlocking do not deadlock each other but form a shared event loop. When the coroutine suspends in someSuspendFunctionForInitialization, nested runBlocking starts executing coroutines from the outer ones, that are able to execute lazy initializer because of lock re-entrancy

@alacoste
Copy link
Author

alacoste commented Dec 1, 2019

It's not exactly that, but the idea is similar.
After #860 nested runBlocking do not deadlock each other but form a shared event loop. When the coroutine suspends in someSuspendFunctionForInitialization, nested runBlocking starts executing coroutines from the outer ones, that are able to execute lazy initializer because of lock re-entrancy

Thanks for the clarification!

@revintec
Copy link

@qwwdfsad coroutine doesn't have identity(unlike thread), so similar bug can't be solved, even in the future?
(this specific lazy val can be solved of course, but similar synchronized or lock reentrant ones

@qwwdfsad
Copy link
Collaborator

It's not exactly an identity problem but rather a corner case of the edge of even loops and reentrant JVM locks. Over the course of years, we haven't really found an elegant solution for this particular problem, so it's unlikely to ba changed in the future

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants