android/codelab-android-room-with-a-view

Not thread-safe implementation of WordRoomDatabase singleton

AlexanderYukhanov opened this issue · 1 comments

Despite of used synchronization primitives the example

public abstract class WordRoomDatabase : RoomDatabase() {

   abstract fun wordDao(): WordDao

   companion object {
        // Singleton prevents multiple instances of database opening at the
        // same time. 
        @Volatile
        private var INSTANCE: WordRoomDatabase? = null

        fun getDatabase(context: Context): WordRoomDatabase {
            // if the INSTANCE is not null, then return it,
            // if it is, then create the database
            return INSTANCE ?: synchronized(this) {
                val instance = Room.databaseBuilder(
                        context.applicationContext,
                        WordRoomDatabase::class.java, 
                        "word_database"
                    ).build()
                INSTANCE = instance
                // return instance
                instance
            }
        }
   }
}

is not thread safe as it allows creation of multiple instances of WordRoomDatabase. Double-Checked Locking needs to be used to make it working.

The code you have provided utilizes the Singleton pattern and synchronized to ensure Thread-safety when creating an instance of the Room database (WordRoomDatabase). In general, this code is Thread-safe. The reason for this assurance of Thread-safety is due to the use of @volatile for the INSTANCE variable and the use of a synchronized block.

In this code:

The INSTANCE variable is declared using @volatile. This ensures that changes made to this variable by one thread are seen by other threads in a non-disjointed manner.

In the getDatabase function, a synchronized block is used before creating a new instance of the database. This synchronized block ensures that only one thread can attempt to create a new instance of the database at any given time. Other threads have to wait until the instance is created, and this access is exclusive.

Therefore, this code correctly employs Thread-safe techniques for creating a Singleton instance of the database and prevents simultaneous creation of multiple instances, making it Thread-safe.