Guy
Guy

Reputation: 13336

What happens to my Singletons when memory is low or when I get a notification while the app is not running

In my app I used the singleton pattern for objects which serve other classes and not more than one instance of them is needed. LocalstorageManager for example:

public class LocalStorage {

    private Context context;

    private static LocalStorage instance = null;

    protected LocalStorage() {
        // Exists only to defeat instantiation.
    }

    public synchronized static LocalStorage getInstance() {
        if (instance == null) {
            instance = new LocalStorage();
        }
        return instance;
    }

    public void setContext(Context _context) {
        instance.context = _context;
    }
    ...

In this app I am using a BroadcastReceiver that responds to GSM notifications:

...
@Override
protected void onPushReceive(Context context, Intent intent) {
     LocalStorage localStorage = LocalStorage.getInstance();
...

Should I check whether my singletons state is set before using them? Is there a chance than on cases of low memory or an incoming GSM when the app is not running I will have to reinstansiate my singletons with their state? If so, should I do it in the custom app class? Would it always be called?

Upvotes: 0

Views: 121

Answers (1)

takrishna
takrishna

Reputation: 5002

  1. Should I check whether my singletons state is set before using them?

Singleton if properly implemented would return only one instance which is common throughout the app life-cycle. Your singleton's state is ensured until unless the Singleton object gets destroyed say as described in point "2" below.

  1. Is there a chance than on cases of low memory or an incoming GSM when the app is not running I will have to reinstansiate my singletons with their state?

Java Garbage Collector (GC) will collect all the objects that are not used/not referenced. Which means if no active object of your app has a "reference"/"is using" this object then the GC will clear it. In such case you may have to instantiate your object. Java GC gets triggered irrespective of "..low memory or an incoming GSM.." it could also be System discretion.

  1. If so, should I do it in the custom app class? Would it always be called?

No, not in custom app class do it in the Singleton class implementation. The method "getInstance()" will take care of when to instantiate a new object Vs when to serve an existing object. If there is any custom state/parameter to instantiate you may want to pass them in getInstance() method.

Upvotes: 0

Related Questions