fun getDatabase(context: Context): InventoryDatabase {
// if the Instance is not null, return it, otherwise create a new database instance.
return Instance ?: synchronized(this) {
Room.databaseBuilder(context, InventoryDatabase::class.java, "item_database")
.build()
.also { Instance = it }
}
}
URL of codelab: https://developer.android.com/codelabs/basic-android-kotlin-compose-persisting-data-room
In which task and step of the codelab can this issue be found? Step 7 - Create a Database instance
Describe the problem In the codelab, Singleton pattern doesn't use double-checked locking. See https://en.wikipedia.org/wiki/Double-checked_locking This can cause double initialization if used in real code.
The code provided is: