Will JVM Garbage Collector Reclaim Long-Unused Singleton Objects?
This article investigates whether the JVM garbage collector can reclaim singleton instances that remain unused for extended periods, presenting a test program, analyzing GC logs, and explaining the GC root mechanism that keeps static singleton references alive, concluding that HotSpot 1.6 does not collect such objects.
The author raises the controversial question of whether a singleton object that is never used again can be reclaimed by the JVM garbage collector, motivated by a claim in a design‑pattern book that long‑unused singletons are treated as garbage in J2EE environments.
To examine this, a test program is provided that creates a singleton occupying 6 MB of heap memory and then enters an infinite loop continuously allocating 3 MB objects, forcing the JVM to perform garbage collection while monitoring memory usage.
The program is run on the HotSpot JVM (JDK 1.6.0_12) with VM arguments -verbose:gc -Xms20M -Xmx20M , which fix the heap size at 20 MB and display GC details.
Observed GC logs consistently show that about 6 MB of memory remains uncollected, indicating that the singleton object is never reclaimed:
……
[Full GC 18566K->6278K(20352K), 0.0101066 secs]
[GC 18567K->18566K(20352K), 0.0001978 secs]
[Full GC 18566K->6278K(20352K), 0.0088229 secs]
……The article explains that HotSpot uses a root‑search algorithm: any object reachable from GC roots (stack frames, static fields, constant pool, JNI references) is considered alive and cannot be collected. Since a singleton is referenced by a static field, it is a GC root and therefore remains alive.
Further discussion covers whether the singleton class itself could be unloaded. The JVM unloads a class only when all its instances are reclaimed, its class loader is reclaimed, and its java.lang.Class object is no longer referenced. Because the singleton instance persists, the class never satisfies the first condition and is not unloaded.
Consequently, the author concludes that, in HotSpot 1.6, the garbage collector will not reclaim a singleton object unless the static reference is explicitly cleared.
Readers are invited to share their opinions on the matter.
Java Captain
Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.