Daniel
10/13/2020, 8:18 PMsynchronize
, or how to understand how it works. Can anyone help me figure out what this actually does? (I figured out it was an internal fn from the warning I got from Android Studio)
// Annotates class to be a Room Database with a table (entity) of the Word class
@Database(entities = arrayOf(Word::class), version = 1, exportSchema = false)
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 {
val tempInstance = INSTANCE
if (tempInstance != null) {
return tempInstance
}
synchronized(this) {
val instance = Room.databaseBuilder(
context.applicationContext,
WordRoomDatabase::class.java,
"word_database"
).build()
INSTANCE = instance
return instance
}
}
}
}
Is all this necessary? How does this differ from the more normal way I've seen people write something to cache a return value, which doesn't use @Volatile
or synchronized
? Something like
private var _cache: WordRoomDatabase? = null
fun getDatabase(context: Context): WordRoomDatabase {
val cached = _cache // also, why is this necessary actually?
if (cached != null) {
return cached
} else {
_cache = Room.databaseBuilder(
context.applicationContext,
WordRoomDatabase::class.java,
"word_database"
).build()
return cache
}
}
Ian Lake
10/13/2020, 8:24 PMsynchronized
, not synchronize
- those are different thingsDaniel
10/13/2020, 8:24 PMsynchronized
is the internal function I got warned about?Ian Lake
10/13/2020, 8:28 PMsynchronized
is not an internal function (nor should you have any import related to synchronized
- that would indicate you are using the wrong one)Ian Lake
10/13/2020, 8:28 PM_cache
version is not thread safeDaniel
10/13/2020, 8:30 PMIan Lake
10/13/2020, 8:32 PMgetDatabase()
from two different coroutines simultaneously is also not safeIan Lake
10/13/2020, 8:33 PMsynchronized
to ensure that only one caller can be inside that block at a timePetter Måhlén
10/14/2020, 6:40 AM