Java – How long a singleton class object exists

How long a singleton class object exists… here is a solution to the problem.

How long a singleton class object exists

I’m working on an android app with a singleton class like this:

public class ClassName {

private static ClassName mobject;
    public List<Question> mquestionslist;

public ClassName() {
        mquestionslist=new ArrayList<Question>();
    }

public static ClassName getInstance() {
        if (mobject == null) {
            mobject = new ClassName();
        }
        return mobject;
    }
    public void LoadQuestions()
    {
       do somthing

}
}

Now every time I want to use this object, I just call ClassName.getInstance().any_method_name() from another activity or fragment and use it directly.
I never create any local references to such objects, for example:

ClassName ref=ClassName.getInstance();
ref.any_method_name();

=> please tell me how long this object can survive before the garbage collector removes it from memory, is it a good habit? (Unable to get an answer from anywhere else).

Solution

The instance you get by calling the “getInstance” method is a static object defined in class “ClassName”.

 private static ClassName mobject;

Until class ‘ClassName’ remains loaded, the instance will not be eligible for garbage collection.

If the classloader used to load “ClassName” is garbage collected, the “ClassName” class is unloaded and the corresponding static object is lost.

Related Problems and Solutions