Let me give you the scenario.
Say that my first Activity that loads up, also creates a thread, which will run indefinitely in the background.
Now, if I move to another Activity, I assume that the thread that I initially created in the main activity will continue to run.
So, now to my main question - in order to manage this background thread from other Activities, is it safe to store a reference to that thread in a singleton object?
Is singleton thread safe? A singleton class itself is not thread safe. Multiple threads can access the singleton same time and create multiple objects, violating the singleton concept. The singleton may also return a reference to a partially initialized object.
Thread Safe Singleton in JavaCreate the private constructor to avoid any new object creation with new operator. Declare a private static instance of the same class. Provide a public static method that will return the singleton class instance variable.
It is thread-safe even if we remove final from public static final Singleton instance = new Singleton (); .
As I understand, Data race can be avoided by making sure that one or more of the above conditions hold false - ie, by making shared variables immutable or by making the access to them properly synchronized .
Yes and no. Theoretically, you will have no problem, but you must not allow references to escape.
Problems can arise from keeping the reference in the singleton object private, it must not pass the reference to anything else or allow access to it by anything else, or it can lose control.
Secondly, the thread created by your activity must not allow access to its member variables or allow references to them to escape.
A good book on this area is "Java Concurrency in Practice" by Brian Goetz
Actually where you need to be careful is if you have multiple class loaders. A Singleton is only a singleton if you are using the same class loader to load the class in. If you have multiple class loaders in your app running the same classes you will have another instance of the singleton in each.
Most standalone apps only use one classloader and therefore do not have any issues. If you have only one classloader then you will be fine.
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