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

There’s a static reference to a singleton, so it won’t be eligible for garbage collection until the classloader is eligible for garbage collection.

You can’t force any object to be garbage collected; you can request that the garbage collector runs with System.gc() but it’s only a request.

If you really want to make a “singleton” eligible for garbage collection, you’d probably want to have a method to set the static variable to null (and hope that nothing else had taken a copy of the reference). Obviously the next time anyone asked for an instance, it would need to be recreated… at which point it’s not really a singleton, of course.

Leave a Comment