Home > Enterprise >  Kotlin Room Database Singleton Pattern
Kotlin Room Database Singleton Pattern

Time:10-21

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

According to this document https://developer.android.com/codelabs/kotlin-android-training-room-database?hl=en&continue=https://codelabs.developers.google.com/?cat=android#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 diffrence between them? In terms of performance or whatever

CodePudding user response:

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

  • Related