Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static singleton class memory leak in android

I have a static singleton class that extends my User object:

public class TestSingleton extends User{

    private static TestSingleton singletonInstance;

    private TestSingleton() {
    }

    public static TestSingleton getObj() {
        if (singletonInstance == null) {
            singletonInstance = new TestSingleton();
        }
        return singletonInstance;
    }
}

The purpose of the singleton is to avoid create new instance any time i want to use my User object in different activities:

TestSingleton test = new TestSingleton();
test.doSomthing();

And to write it on one line and create instance only one time in my app life cycle:

TestSingleton.getObj().doSomthing();

My question is:

Is this use of static Singleton create memory leak and hold reference to any activity I use the singleton?

Is it safe to use? or there is a better solution?

like image 799
user3616871 Avatar asked Nov 23 '22 08:11

user3616871


1 Answers

Is this use of static Singleton create memory leak and hold reference to any activity I use the singleton?

it won't in the 99.9% of cases,

Is it safe to use?

That depends on what you mean by safe. Your implementation it is not thread safe, for instance. if you call getObj() from two different threads can happen that you instantiate TestSingleton twice.

 or there is a better solution?

There is an implementation of the Singleton pattern that makes use of the Enum. You can find an example on Effective Java

like image 159
Blackbelt Avatar answered Dec 15 '22 02:12

Blackbelt