I'm trying to move everything in my app away from singletons, because I've been made aware that it's a bad programming practice, with that said, I'm looking into implementing Dagger 2 dependency injection. And I'm wondering, when you do @Singleton in Dagger 2 is that thread synchronized? if not how can I synchronize it, so I don't get any strange data anomalies from multiple threads touching the same things.
When I was creating singletons before I'd do something like this:
public class SomeSinglton {
private static ClassName sInstance;
private SomeSinglton () {
}
public static synchronized ClassName getInstance() {
if (sInstance == null) {
sInstance = new ClassName();
}
return sInstance;
}
is the Dagger 2 @Singleton equivalent as far as being synchronized?
The @Singleton annotation is used to declare to Dagger that the provided object is to be only initialized only once during the entire lifecycle of the Component which uses that Module.
It is thread-safe even if we remove final from public static final Singleton instance = new Singleton (); . That's because the JVM guarantees that the instance will be created before any thread access the static instance variable.
Singleton pattern in java that is Thread safe, Reflection proof, can be used with serialization.
While we are using multithreading access to a singleton instance can be performed from various threads it could be a problem while constructing singleton instances. If you are in Singleton::Instance() and receive an interrupt, invoke Singleton::Instance() from another thread, you can see how you'd get into trouble.
Yes, @Singleton
s in Dagger 2 are thread safe with double checked locking, same in Dagger 1. See ScopedProvider
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With