The Artima Developer Community
Sponsored Link

Legacy Java Answers Forum
June 2000



This page contains an archived post to the Java Answers Forum made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.



Posted by Matt Gerrans on July 01, 2000 at 2:54 AM

In the section "Garbage Collection and Finalization of Objects," Venners says "Implentations [of JVMs] can decide when to garbage collect unreferenced objects -- or even decide whether to garbage collect them at all." This implies that gc() is only a suggestion that it is okay by you (performance-wise, I would imagine) for the garbage collection to do its thing. Eckel's book also implies this under "Order of garbage collection," though he doesn't specifically mention gc(), either.

Several books have it outright wrong and state that gc() forces garbage collection (maybe you saw one of these).

The specification is pretty clear on the subject: "Calling this method suggests that the Java Virtual Machine expend effort toward recycling discarded objects in order to make the memory they currently occupy available for quick reuse. When control returns from the method call, the Java Virtual Machine has made a best effort to recycle all discarded objects." The key word being "suggests," of course. Like the old "register" keyword in C/C++.

So the answers to your questions are:
- When it deems it necessary.
- The implementation of the JVM you are using didn't think garbage collection was warranted at the point you suggested (which is not too surprizing, as you had only worked with a few bytes -- try an array of a few million books and see if it kicks in!).

- Matt

> class Book{
> boolean checkedOut = false;
> Book(boolean checkOut){
> checkedOut = checkOut;
> }
> void checkIn(){
> checkedOut = false;
> }
> public void finalize(){
> if(checkedOut)
> System.out.println("Error : checked out");
> }
> }
> public class DeathCondition{
> public static void main(String[] args){
> Book novel = new Book(true);
> novel.checkIn();
> new Book(true);
> System.out.println("ABC"); //22
> System.gc();
> }
> }
> When garbage collecter does its job?
> and why does not the above program print "Error : checked out" without Line 22 ?


Sponsored Links

Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us