0

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?

Free Coder
  • 459
  • 4
  • 19

1 Answers1

1

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.

Community
  • 1
  • 1
eribeiro
  • 572
  • 3
  • 7
  • How about in the case when the Singleton is implemented with the use of Enum ? – Free Coder Sep 03 '15 at 04:07
  • See that, in the original question, if we have a static field in a class referencing an object and we set it to null then the object previously referenced by it can be GC'ed, but doing so we break the singleton pattern. – eribeiro Sep 03 '15 at 04:22
  • What about for Swift? Anyone have any tests to verify this? Or any official apple docs? – spnkr Jan 26 '23 at 16:50