Is it safe to maintain a link to a stream in singleton mode?

Let me tell you the script.

Say that my first activity, which is loading, also creates a thread that will run endlessly in the background.

Now, if I move on to another Office, I assume that the thread that I originally created in the main action will continue to work.

So now, to my main question - in order to manage this background thread from other Acts, is it safe to store a link to this thread in a singleton object?

+6
java android multithreading singleton
source share
2 answers

Yes and no. Theoretically, you will not have problems, but you should not allow escape to be referenced.

Problems can arise due to saving the link in a separate private object, it should not pass the link to anything else or allow access to it with something else, or it may lose control.

Secondly, the stream created by your activity should not allow access to its member variables or allow links to them.

A good book in this area is Brian Goetz's Java Concurrency in Practice.

+4
source share

In fact, you need to be careful if you have multiple class loaders. Singleton is only a singleton if you use the same classloader to load the class. If you have multiple class loaders in your application using the same classes, you will have another instance of the singleton in each.

Most standalone applications use only one class loader, and therefore there is no problem. If you have only one classloader, then everything will be fine.

+2
source share

All Articles