Search code examples
garbage-collectionsingletonsingleton-methods

When is a singleton class object garbage collected?


If a single instance of class is created using singleton pattern, if it is not referenced for a long time, if a GC finds an unrooted tree whose leaf is the Singleton instance, will it be garbage collected?


Solution

  • Well, singleton pattern is implemented by defining a private static field, a private construtor and a static method that returns the field. So, the question boils down to: a static field is garbaged collected?

    The answer is no, at least according to this SO answer: Do static members ever get garbage collected?

    So, even if there is no other references to the static field it will not be GC'ed.