Java Reference
In-Depth Information
To invoke these methods you need to obtain a reference to the current
Runtime object via the static method Runtime.getRuntime . The System class
supports static gc and runFinalization methods that invoke the corres-
ponding methods on the current Runtime ; in other words, System.gc() is
equivalent to Runtime.getRuntime().gc() .
The garbage collector may not be able to free any additional memory
when Runtime.gc is invoked. There may be no garbage to collect, and
not all garbage collectors can find collectable objects on demand. So in-
voking the garbage collector may have no effect whatsoever. However,
before creating a large number of objectsespecially in a time-critical ap-
plication that might be affected by garbage-collection overheadinvoking
gc may be advisable. Doing so has two potential benefits: You start with
as much free memory as possible, and you reduce the likelihood of the
garbage collector running during the task. Here is a method that ag-
gressively frees everything it can at the moment:
public static void fullGC() {
Runtime rt = Runtime.getRuntime();
long isFree = rt.freeMemory();
long wasFree;
do {
wasFree = isFree;
rt.runFinalization();
rt.gc();
isFree = rt.freeMemory();
} while (isFree > wasFree);
}
This method loops while the amount of freeMemory is being increased
by successive calls to runFinalization and gc . When the amount of free
memory doesn't increase, further calls will likely do nothing.
You will not usually need to invoke runFinalization , because finalize
methods are called asynchronously by the garbage collector. Under
some circumstances, such as running out of a resource that a finalize
method reclaims, it is useful to force as much finalization as possible.
 
Search WWH ::




Custom Search