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?
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
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