简体   繁体   English

是@Singleton在匕首2线程安全吗?

[英]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. 我试图将我的应用程序中的所有内容从单例中移开,因为我已经意识到这是一个糟糕的编程习惯,据说,我正在考虑实现Dagger 2依赖注入。 And I'm wondering, when you do @Singleton in Dagger 2 is that thread synchronized? 我想知道,当你在Dagger 2中做@Singleton时,该线程是否同步? 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? 就同​​步而言,Dagger 2 @Singleton等效吗?

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

As Artem Zinnatullin mentioned in his answer - instance creation of @Singleton classes is thread safe in Dagger. 正如Artem Zinnatullin在他的回答中提到的 - @Singleton类的实例创建在Dagger中是线程安全的。

But if you are going to touch that singleton from different theads you must make it thread safe by yourself. 但是如果你打算从不同的theads中触摸那个单身人士,你必须自己使它成为线程安全的。 Otherwise Dagger won't help you. 否则Dagger不会帮助你。

Usually, @Singleton annotation should mean for other developers that such class can be used from different threads. 通常,@ Singleton注释应该对其他开发人员来说意味着可以从不同的线程使用这样的类。

Loot at this site . 这个网站抢劫。 There are different approaches to implement Singleton, among them ThreadSafeSingleton 实现Singleton有不同的方法,其中包括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. 当静态字段sInstance被初始化时,存在隐式同步。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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