I have been looking at some Google sample code and they seem to create a singleton using the the following code:
companion object {
// For Singleton instantiation
@Volatile
private var instance: CarRepository? = null
fun getInstance(carDao: CarDao) =
instance ?: synchronized(this) {
instance ?: CarRepository(carDao).also { instance = it }
}
}
So I know @Volatile
means that
Marks the JVM backing field of the annotated property as volatile, meaning that writes to this field are immediately made visible to other threads.
Should all Singletons instances always be marked as @Volatile
? If so, why?
Lastly, I don't understand the getInstance
function
instance ?: synchronized(this) {
instance ?: CarRepository(carDao).also { instance = it }
}
What is it exactly doing here?
UPDATE:
Source: Google's Sunflower
I changed the Repository and Dao name for my own use, but it is the same logic in the Repository
files.