...
Since JDK 1.2, the generational garbage collector has reduced memory allocation costs to low levels, in many cases lower than in C or C++. Generational garbage collection reduces garbage collection costs by grouping objects into generations. The younger generation consists of short-lived objects. The garbage collector performs a minor collection on the younger generation when it fills up with dead objects [Oracle 20102010a]. Improved garbage-collection algorithms have reduced the cost of garbage collection so that it is proportional to the number of live objects in the younger generation rather than to the number of objects allocated since the last garbage collection.
Note that objects in the younger generation that persist for longer durations are tenured and are moved to the tenured generation. Few younger-generation objects continue to live through to the next garbage-collection cycle. The rest become ready to be collected in the impending collection cycle [Oracle 20102010a].
With generational garbage collectors, use of short-lived immutable objects is generally more efficient than use of long-lived mutable objects, such as object pools. Avoiding object pools improves the garbage collector's efficiency. Object pools bring additional costs and risks: they can create synchronization problems and can require explicit management of deallocations, possibly creating problems with dangling pointers. Further, determining the correct amount of memory to reserve for an object pool can be difficult, especially for mission-critical code. Use of long-lived mutable objects remains appropriate when allocation of objects is particularly expensive (for example, when performing multiple joins across databases). Similarly, object pools are an appropriate design choice when the objects represent scarce resources, such as thread pools and database connections.
...
The Apache Geronimo and Tomcat vulnerability GERONIMO-4574, reported in March 2009, resulted from PolicyContext
handler data objects being set in a thread and never released, causing these data objects to remain in memory longer than necessary.
Related Guidelines
Bibliography
[API 2011] | |
Item 6, "Eliminate Obsolete Object References" | |
"Garbage Collection Concepts and Programming Tips" | |
Java Theory and Practice: Garbage Collection and Performance | |
[Lo 2005] | |
[Oracle 20102010a] | Java SE 6 HotSpot™ Virtual Machine Garbage Collection Tuning |
...