I have a Singleton class which I use with the one of the activities of my application.
When I exit the activity - which brings me back to the menu activity - and then reopen the activity I find that when I try to access the singleton it is still the same. Surely it should have been destroyed with the Activity?
I saw the question here: living singleton, when activity end but could not quite follow what they mean.
When I press the return button on my device (or use finish within the Activity itself) is the Activity kept alive for future use? If so, then that would explain it.
1)Private constructor to restrict instantiation of the class from other classes. 2)Private static variable of the same class that is the only instance of the class. 3)Public static method that returns the instance of the class, this is the global access point for outer world to get the instance of the singleton class.
Singleton pattern is used for logging, drivers objects, caching and thread pool. Singleton design pattern is also used in other design patterns like Abstract Factory, Builder, Prototype, Facade etc. Singleton design pattern is used in core java classes also, for example java. lang.
A singleton should be used when managing access to a resource which is shared by the entire application, and it would be destructive to potentially have multiple instances of the same class. Making sure that access to shared resources thread safe is one very good example of where this kind of pattern can be vital.
Singletons are references attached to classes, just as classes are global references these are not reached by the garbage collector. In case the Singleton is a complex object, this entire object, in addition to the transitive closure of all its references, will stay in memory throughout the execution.
Surely it should have been destroyed with the Activity?
No.
When I press the return button on my device (or use finish within the Activity itself) is the Activity kept alive for future use?
The activity is not. The process is. Singletons are part of the virtual machine and will live as long as the process does. Exiting the last activity does not immediately terminate the process, so the singleton lives on... at least for a while.
Android will eventually terminate that process to free up memory for other apps. How quickly it will do that depends on what the user is doing, what apps are installed, phase of the moon, etc.
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