Re: Forcing System.gc()
R. Vince wrote On 06/07/07 09:42,:
I have an app that, at one point, really bogs down as so many objects are
created and released in a lengthy process.
I am wondering if I may not be able to improve performance by System.gc() in
some "right" places in my code (wherever those might be!). It seems to me
though, that the gc facilities in Java are so good, that this is something
best left up to the JVM, and NOT mess with putting System.gc() in anyplace?
The usual wisdom is that the JVM has a more accurate
idea of the state of memory than you do. Its decisions
about when to collect garbage, since they are made in
light of the actual run-time memory pressure, are likely
to be better than static decisions you make at coding
time without benefit of the JVM's knowledge.
In very rare cases you might do better than the JVM,
because the knowledge advantage is not entirely one-sided.
The JVM has better information than you do on the current
state and recent history of memory, but has no knowledge
of the program's future behavior. You may be able to
exploit your foreknowledge to choose a better moment for
GC than the JVM would if left to its own devices.
... but such cases are likely to be extremely rare.
About the only scenario I can come up with is a program
that runs in "waves:" it creates a huge population of
objects, then throws nearly all of them away, and then
repeats. You might get some advantage by running GC in
the "troughs," just after the great object die-off and
before the ensuing population boom. But that's "might"
as in "it's conceivable, I suppose," and not a promise of
any benefit -- it's not even a promise of no harm!
Suggestion: Gather some statistics on the actual GC
behavior of your program. If you find that GC is a problem,
your next step should be to find out why it runs so often
and so hard: Are you creating and discarding objects sub-
optimally, as in
String s = "";
for (String s2 : hugeCollectionOfStrings)
s += s2;
Reducing "object churn" will probably do more to help with
GC than quite a lot of GC-centered fiddling. (Memory
profilers may also be of help here.)
If GC is still a problem even after you've done all you
can to use your objects intelligently, then and only then
should you resort to fiddling with the GC itself. And if
you do, be sure to measure what happens and compare with
the original, pre-fiddling measurements: "tuning" GC may
actually have made things worse, and it may be necessary to
"de-tune" it just to recover the status quo ante.