Java Reference
In-Depth Information
Use Short-Lived Immutable Objects
Beginning with JDK 1.2, the generational GC has reduced memory allocation costs, in
many cases to levels 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 GC performs a minor collection on the younger gen-
eration when it fills up with dead objects [Oracle 2010a]. Improved garbage collection al-
gorithms have reduced the cost of garbage collection so that it is proportional to the num-
berofliveobjectsintheyoungergeneration,ratherthantothenumberofobjectsallocated
since the last garbage collection.
Notethatobjectsintheyoungergenerationthatpersistforlongerdurationsare tenured
andaremovedtothe tenured generation .Fewyounger-generationobjectscontinuetolive
through to the next garbage-collection cycle. The rest become ready to be collected in the
impending collection cycle [Oracle 2010a].
WithgenerationalGCs,useofshort-livedimmutableobjectsisgenerallymoreefficient
than use of long-lived mutable objects, such as object pools. Avoiding object pools im-
proves the GC's efficiency. Object pools bring additional costs and risks: they can cre-
ate synchronization problems and can require explicit management of deallocations, pos-
sibly 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.
Avoid Large Objects
The allocation of large objects is expensive, in part because the cost to initialize their
fields is proportional to their size. Additionally, frequent allocation of large objects of dif-
ferent sizes can cause fragmentation issues or compacting collect operations.
Do Not Explicitly Invoke the Garbage Collector
The GC can be explicitly invoked by calling the System.gc() method. Even though the
documentation says that it “runs the garbage collector,” there is no guarantee as to when
or whether the GC will actually run. In fact, the call merely suggests that the GC should
subsequently execute; the JVM is free to ignore this suggestion.
Irresponsible use of this feature can severely degrade system performance by trig-
gering garbage collection at inopportune moments, rather than waiting until ripe periods
Search WWH ::




Custom Search