Hi Everyone, out of curiosity, I have a question. ...
# kontributors
a
Hi Everyone, out of curiosity, I have a question. Why does Kotlin use eager initialization for object classes internally? Can someone share the design rationale behind choosing this approach over double-checked locking?
e
classes are loaded on demand on JVM, so double-checked locking has no benefit in singleton object classes
a
Thanks for the reply! Is there any correlation with coroutines, since Java's synchronization isn't coroutine-friendly? lets say for this code👇
Copy code
object Singleton{
  suspend fun test(){
      ...
  }
}
we will access this
test()
method from coroutine, and there might be some possibility of synchronization issue?
e
no. the first user of
Singleton
will block in the classloader, under the class loading lock, until the object is initialized. that is JVM behavior
a
Apologies, let me clarify my question: Since Java's synchronization isn't coroutine-friendly, did Kotlin choose eager initialization to avoid potential issues that could arise if a double-checked locking approach were used with
object
classes inside coroutines? Is there any correlation with coroutines then?
e
no correlation