0

Ok so I'm trying to keep a singleton instance of GetItemQuery which is a POJO to hold the requests and response fields needed for Retrofit API calls. I dont need to create a new GetItemQuery every time I make a call, hence I'm using the singleton pattern to set the fields of the existing GetItemQuery instance.

public class GetItemQuery {

    // request data
    private String itemId;
    private int numberToLoad;
    // response data
    private Item item;

    private static class Loader {
        static final GetItemQuery sInstance = new GetItemQuery();
    }

    public static GetItemQuery getInstance(Item item) {
        GetItemQuery instance = Loader.sInstance;
        instance.setItem(item);
        return instance;
    }

    public Item getItem() {
        if (item == null) {
            item = new Item();
        }
        return item;
    }

    public void setItem(Item item) {
        this.item = item;
    }    

     // other getters and setters
 }

in my Android app. At what points should I be worried that getInstance() will be garbage collected so all the fields are cleared? Or is there a way for me to manually garbage collect so I ensure some fields don't become null unexpectedly?

bycfly
  • 341
  • 3
  • 13
  • 2
    This appears to be a duplicate of this question: https://stackoverflow.com/questions/4127458/when-would-the-garbage-collector-erase-an-instance-of-an-object-that-uses-single – Gerik Apr 12 '18 at 06:56
  • 1.) It will never be garbage collected as long as there is a reference to the object. Static references are references. In other words: Won't be GC until your application stops running. 2.) When using Singletons (which is a decision you should not make just like this) please use the `enum`-implementation. It's the best way to make a Singleton in Java. Compare [here](https://stackoverflow.com/questions/26285520/implementing-singleton-with-an-enum-in-java). – Ben Apr 12 '18 at 06:57
  • 1
    Possible duplicate of [When would the garbage collector erase an instance of an object that uses Singleton pattern?](https://stackoverflow.com/questions/4127458/when-would-the-garbage-collector-erase-an-instance-of-an-object-that-uses-single) – Ben Apr 12 '18 at 06:59

1 Answers1

0

Like described in this answer:

When would the garbage collector erase an instance of an object that uses Singleton pattern?

It will not be garbage collected, because there is a static reference

Ron Nabuurs
  • 1,528
  • 11
  • 29
  • The linked question is a duplicate of this one. You should have probably flagged it as such over just pasting a link as an answer. – Ben Apr 12 '18 at 06:59