Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is @Singleton in dagger 2 thread safe?

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?

like image 807
AlexW.H.B. Avatar asked May 14 '15 14:05

AlexW.H.B.


People also ask

What does @singleton annotation do?

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.

Is eager initialization thread-safe?

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.

Is singleton design pattern is thread-safe?

Singleton pattern in java that is Thread safe, Reflection proof, can be used with serialization.

Can we use singleton class in multithreading?

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.


1 Answers

Yes, @Singletons in Dagger 2 are thread safe with double checked locking, same in Dagger 1. See ScopedProvider.

like image 152
Artem Zinnatullin Avatar answered Sep 30 '22 05:09

Artem Zinnatullin