When would the garbage collector erase an instance of an object that uses Singleton pattern?
When would the garbage collector erase an instance of an object that uses Singleton pattern?
Does an object hang around any longer than a regular object?
How can you manually force deletion/garbage collection of an object in开发者_JS百科 Java?
Thanks.
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.
There are special objects in Java called GC roots. They are always reachable and so are the objects that can be reached from these roots. These GC roots can never be garbage collected and so do the objects that are reachable from these roots. In Java static variables form GC roots.
Singleton class has a static reference to the instantiated singleton object and hence it will never be garbage collected unless ofcourse as Jon Skeet as stated that the context that loaded this class (class loader) is itself eligible for garbage collection in which case that static reference will not longer be a GC root.
Relevant answer here.
I think this was a bug prior to Java 1.2 when singleton instance could be garbage collected if there was no global reference to it but that was fixed in Java 1.2 and only way now it can be eligible for garbage collection is if the class loader that loaded this class was garbage collected.
If you're keeping a static reference to it in your singleton class, then the reference count cannot drop to 0 and therefore it shouldn't ever get collected.
static
fields can and do get GCed however this doesn't happen in a simple application.
The static fields are referenced by the Class and the Class is referenced by the ClassLoader. The ClassLoader is referenced by every class and every instance of that class.
However in OSGi containers and application servers it is not unusual to drop every reference to an application or library and it's class loader. At this point the class loader and every static field can be GC-ed.
精彩评论