简体   繁体   中英

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?

是的,@ @Singleton在Dagger 2中具有双重检查锁定的线程安全性,在Dagger 1中ScopedProvider 。请参阅ScopedProvider

As Artem Zinnatullin mentioned in his answer - instance creation of @Singleton classes is thread safe in Dagger.

But if you are going to touch that singleton from different theads you must make it thread safe by yourself. Otherwise Dagger won't help you.

Usually, @Singleton annotation should mean for other developers that such class can be used from different threads.

Loot at this site . There are different approaches to implement Singleton, among them ThreadSafeSingleton

There's nothing wrong with singletons. But this is a better implementation.

public class SomeSinglton {
    private static ClassName sInstance = new SomeSinglton();

    private SomeSinglton () {
    }

    public static ClassName getInstance() {
        return sInstance;
    }

There's an implicit synchronization when the static field sInstance is initalized.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM