@ Singleton in dagger 2 is thread safe?

I am trying to move everything in my application alone because I became aware that this is a bad programming practice and I said that I am studying dagger 2 dependency injection. And I wonder when you do @Singleton in Dagger 2, this thread is synchronized ? if not, how can I synchronize it, so I don’t get any strange data anomalies from multiple streams affecting the same things.

When I created singlets, before I would 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 equivalent of @ @ Singleton's dagger until it synchronizes?

+6
source share
4 answers

As Artem Zinnatullin mentioned in his answer - creating instances of @Singleton classes is thread safe in the dagger.

But if you are going to touch this singleton from different gardens, you must make it thread safe yourself. Otherwise, the dagger will not help you.

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

0
source

Yes, @Singleton in dagger 2 are thread safe with double check locks, same in dagger 1. See ScopedProvider .

+5
source

There is nothing wrong with singles. But this is the best implementation.

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

There is implicit synchronization when the sInstance static field sInstance initialized.

0
source

Loot at this site . There are various approaches to implementing Singleton, including ThreadSafeSingleton

-1
source

Source: https://habr.com/ru/post/987207/


All Articles