However, the virtual machine invokes finalize at most once on any object, even if that object becomes
unreachable more than once because a previous finalize resurrected it. If resurrecting objects is important
to your design, the object would be resurrected only onceprobably not the behavior you wanted.
If you think you need to resurrect objects, you should review your design carefullyyou may uncover a flaw. If
your design review convinces you that you need something like resurrection, the best solution is to clone the
object or create a new object, not to resurrect it. The finalize method can insert a reference to a new
object that will continue the state of the dying object rather than a reference to the dying object itself. Being
new, the cloned object's finalize method will be invoked in the future (if needed), enabling it to insert yet
another copy of itself in yet another list, ensuring the survival, if not of itself, at least of its progeny.
17.4. Interacting with the Garbage Collector
Although the language has no explicit way to dispose of unwanted objects, you can directly invoke the
garbage collector to look for unused objects. The Runtime class, together with some convenience methods
in the System class, allows you to invoke the garbage collector, request that any pending finalizers be run, or
query the current memory state:
public voidgc()
Asks the virtual machine to expend effort toward recycling unused objects so
that their memory can be reused.
public voidrunFinalization()
Asks the virtual machine to expend effort running the finalizers of objects
that it has found to be unreachable but have not yet had their finalizers run.
public longfreeMemory()
Returns an estimate of free bytes in system memory.
public longtotalMemory()
Returns the total bytes in system memory.
public longmaxMemory()
Returns the maximum amount of memory, in bytes, that the virtual machine
will ever attempt to use. If there is no limit, Long.MAX_VALUE is returned.
There is no method to set the maximum; a virtual machine will typically have
a command-line or other configuration option to set the maximum.
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 corresponding 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
invoking the garbage collector may have no effect whatsoever. However, before creating a large number of
objectsespecially in a time-critical application 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,