I am learning dependency injection with Hilt and Dagger and I want to know... When creating classes with the Singleton pattern, should I use a real Singleton or the Hilt annotation? I searched on the internet but could not find a conclusive solution that shows the difference, also when I click to open the generated file from Hilt it does not looks like a Singleton, is it "threadissuesproof"?
"Real Singleton", like this:
class SongController private constructor() {
companion object {
@Volatile
private var INSTANCE: SongController? = null
fun getInstance(): SongController {
synchronized(this) {
var instance = INSTANCE
if (instance == null) {
instance = SongController()
INSTANCE = instance
}
return instance
}
}
}
}
Or the @Singleton annotation from Hilt?
@Singleton
class SongController @Inject constructor() {}
Is there any benefits of using the annotation or the best and safe option is still the getInstace() -> synchronized() block?
Which one should I use in this case?
And the most important question that I did not understand, will the annotation behave the same way?