Speedy
Speedy

Reputation: 1554

Singleton gets recycled

I have a singleton in Android for data loaded from xml. It gets recycled from time to time and I don't understand why. Singleton should exist through the lifetime of app process by my knowledge. Here's my singleton:

public class DataLib {

    public static CategoryList categories = new CategoryList();
    public static RegionList regions = new RegionList();
    public static CompanyTypeList types = new CompanyTypeList();
    public static SearchData searchData = new SearchData();
    public static CompaniesList companies = new CompaniesList();

    private static RegionData currentRegion;

    private static final DataLib INSTANCE = new DataLib();

    protected DataLib() {
    }

    public static DataLib getInstance() {
        return INSTANCE;
    }

    public static void loadData() {
        loadCategories();
        loadRegions();
        loadTypes();
    }

    /* ... some more static functions are here ...*/
}

As you can see it is not instantiated by any activity directly but rather by the process itself. The data are loaded by calling DataLib.loadData() when the application starts = activity which will end when the data are loaded.

I cannot tell for sure what triggers the recycling - sometimes app needs to stay in the background for longer time, sometimes it's in a few minutes. I am logging the pointer of the DataLib class so I can tell that it truly changed = got recycled.

Any ideas? Thanks.

EDIT: Answer is partially in marked answer + comments to it.

Upvotes: 0

Views: 431

Answers (1)

CommonsWare
CommonsWare

Reputation: 1006769

It gets recycled from time to time and I don't understand why.

Android will terminate your process "from time to time".

sometimes app needs to stay in the background for longer time, sometimes it's in a few minutes

The OS and the user can get rid of your process whenever they feel like it. Singletons and other static data members need to be caches for persistent data, loading that data using background threads and the like.

If there is particular work that you are doing in the background, you should be using a Service for that, to indicate to the OS that you are doing work in the background independent of any activities. That does not prevent Android from terminating your process (e.g., at user request), but it will make it a bit less likely to terminate your process on its own (i.e., the OS will tend to choose other processes).

Upvotes: 3

Related Questions