google-developer-training / basic-android-kotlin-compose-training-inventory-app

Apache License 2.0
77 stars 84 forks source link

Race condition in InventoryDatabase #84

Open alexbft opened 8 months ago

alexbft commented 8 months ago

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:

        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 }
            }
        }