Search code examples
androidkotlinsingletonandroid-room

Kotlin Room Database Singleton Pattern


I am trying to create singleton room database. I found 2 solutions but I don't know what's difference between them.

According to this document https://developer.android.com/codelabs/kotlin-android-training-room-database?hl=en&continue=https%3A%2F%2Fcodelabs.developers.google.com%2F%3Fcat%3Dandroid#5

companion object {
    @Volatile private var INSTANCE:AppDatabase? = null
    fun getInstance(context: Context):AppDatabase {
        synchronized(this){
            var instance = INSTANCE

            if (instance == null){
                instance = Room.databaseBuilder(context.applicationContext,AppDatabase::class.java,"user_table")
                    .fallbackToDestructiveMigration()
                    .build()
                INSTANCE = instance
            }
            return instance
        }
 }

And this one according to Singleton class in Kotlin

companion object {
fun getInstance(context: Context):AppDatabase{
        return Room.databaseBuilder(context.applicationContext,AppDatabase::class.java,"user_table")
            .fallbackToDestructiveMigration()
            .build()
    }
}

I tried these and they all give me same instance. Is there any difference between them? In terms of performance or whatever


Solution

  • The differences is the first solution is multi-thread safe instantiation. These will help to prevent different thread re-instantiating your database instance

    If you notice, there is @Volatile and synchronized(this) block there.

    1. @Volatile here helps to immediately made the changes to var INSTANCE:AppDatabase visible to other threads
    2. synchronized(this) will ensure only one thread that accessing this block

    Found several source explaining about multi-thread safe and race condition, and I think this one also found may be helpful to understand in what kind of condition that should using multi-thread safe way