Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to keep a reference to a thread in a singleton?

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?

like image 840
xil3 Avatar asked Nov 15 '10 10:11

xil3


People also ask

Is singleton class thread-safe?

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.

How can you make a singleton class thread-safe?

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.

Is eager initialization thread-safe?

It is thread-safe even if we remove final from public static final Singleton instance = new Singleton (); .

How can we prevent race condition in Singleton design pattern?

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 .


2 Answers

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

like image 89
Jaydee Avatar answered Sep 28 '22 04:09

Jaydee


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.

like image 27
Romain Hippeau Avatar answered Sep 28 '22 03:09

Romain Hippeau