Re: Forcing garbage collection
Dan wrote:
Hello Java Guru's!
Is there a way to force garbage collection in Java?
Before anyone answers I feel I need to state:
- I know about System.gc() and Runtime.gc() and what they do
- I am not suggesting to do this in production code
The purpose of my asking is that I want to test a finializer during a
unit test by allowing something to go out of scope naturally. The
reason why I need it to fall out of scope instead of calling the
finalizer directly is because I am testing that no other references
exist and that the act of letting it fall out of scope makes it
eligible for gc.
You should not, of course, call finalize() directly.
If I understand correctly, you've got a Thing instance to
which there should be only one reference (or hard reference),
and you want to assert "No other (hard) references exist" by
letting the lone reference go out of scope and then seeing
whether the garbage collector agrees that there are no others.
This latter you hope to do by seeing whether the finalize()
method gets called.
The problem with this approach, it seems to me, is that
it's not clear how long you should wait before concluding that
the Thing has not become garbage. You can call System.gc() --
you can even call it several times, creating megabytes of other
garbage between calls -- but I don't know of any way to be sure
finalize() gets called "promptly." If you *do* observe finalize()
being called, fine -- but if you don't, you won't know whether the
test has failed or whether you needed to wait a little longer and
run GC a few more times.
I suppose you could run some simple experiments to get a feel
for how many GC cycles and how much garbage is needed to be
reasonably sure that finalize() will run. Run the experiments
with all available GC flavors, in client and server settings,
and hope for the best, I guess.
I wonder if you could do something more direct, possibly
using a ReferenceQueue or something else in the java.lang.ref
package. I confess I've used only a few of the things therein,
and only in simple ways, so this isn't so much an Answer as an
Exercise for the Reader ...
Good luck!
--
Eric Sosman
esosman@ieee-dot-org.invalid