Previous
Index

Next


Chapter 3) Garbage Collection

Objective 1,2 & 3

State the behaviour that is guaranteed by the garbage collection systemWrite code that explicitly makes objects eligible for garbage collection. Recognize the point in a piece of source code at which an object becomes eligible for garbage collection.

Why would you want to collect the garbage?

You can be a very experienced Java programmer and yet may never had to familiarise yourself with the details of garbage collection. Even the expression garbage collection is a little bizarre. In this context it means the freeing up of memory that has been allocated and used by the program. When the memory is no longer needed it can be considered to be garbage, i.e. something that is no longer needed and is simply cluttering up the living space.

One of the great touted beauties of the Java language is that you don't have to worry about garbage collection. If you are from a Visual Basic background it may seem absurd that any system would not look after this itself. In C/C++ the programmer has to keep track of the allocation and deallocation of memory by hand. As a result "memory leaks" are a big source of hard to track bugs. This is one of the reasons that with some versions of Microsoft applications such as Word or Excel, simply starting and stopping the program several times can cause problems. As the memory leaks away eventually the whole system hangs and you need to hit the big red switch. Somewhere in those hundreds of thousands of lines of C++ code, a programmer has allocated a block of memory but forgot to ensure that it gets released.

Java and garbage

Unlike C/C++ Java automatically frees up unused references. You don't have to go through the pain of searching for allocations that are never freed and you don't need to know how to alloc a sizeof a data type to ensure platform compatibility. So why would you want to know about the details of garbage collection? Two answers spring to mind, one is to pass the exam and the other is to understand what goes on in extreme circumstances.

If you write code that creates very large numbers of objects or variables it can be useful to know when references are released.  If you read the newsgroups you will see people reporting occasions of certain Java implementations exhausting memory resources and falling over. This was not in the brochure from Sun when they launched Java.

In keeping with the philosophy of automatic garbage collection, you can suggest or encourage the JVM to perform garbage collection but you can not force it.

Key Concept Logo

Let me re-state that point, you cannot force garbage collection, just suggest it



A guaranteed behaviour: finalize

Java guarantees that the finalize method will be run before an object is Garbage collected. Note that unlike most other Garbage collection related behaviour this is guaranteed. But what exactly does a finalize method do?

At first glance finalisation sounds a little like the destructors in C++ used to clean up resources before an object is destroyed. The difference is that Java internal resources do not need to be cleaned up during finalisation because the garbage collector looks after memory allocation. However if you have external resources such as file information, finalisation can be used to free external resources. Here is a quote from the JDK1.4 documentation on the finalize method.

Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.

Because garbage collection is “non deterministic” ie you cannot predict when it will happen, you thus cannot predict exactly when the finalize method will run. You will probably be pleased to know that the exam does not expect you to know much (anything?) about the finalize method.

Garbage collection is a tricky one to write exercises with or practice with as there is no obvious way to get code to indicate when it is available for garbage collection. You cannot write a piece of code with a syntax like

if(EligibleForGC(Object){ //Not real code
    System.out("Ready for Garbage");
    }

Because of this you just have to learn the rules. To re-state.

Once a variable is no longer referenced by anything it is available for garbage collection.

You can suggest garbage collection with System.gc(), but this does not guarantee when it will happen

Local variables in methods go out of scope when the method exits. At this point the methods are eligible for garbage collection. Each time the method comes into scope the local variables are re-created.


Unreachability

An object becomes eligible for garbage collection when it becomes unreachable by any code. Two ways for this to happen are when it is explicitly set to null and when the reference that points to it is pointed to some other object. You may get an exam question that has some code that sets a reference to null and you have to work out where the object becomes eligible for garbage collection. This type of question should be easy. The other type where a reference gets pointed at another object is not quite so obvious. Take the following code example.

Key Concept Logo

An object becomes eligible for garbage collection when it becomes unreachable


class Base{
    String s;
    Base(String s){
    this.s = s;
    }
    public void setString(String s){
    this.s = s;
    }
}
public class UnReach{
    public static void main(String argv[]){
    UnReach ur = new UnReach();
    ur.go();
    }
    public void go(){
    Base b1 = new Base("One");
    b1.setString("");
    Base b2 = new Base("Two");
    b1 = b2;

    }

At what point does the object referenced by b1 become eligible for garbage collection.? Assuming you are ignoring the nonsense about setting the string to blank you will have worked out that when b1 is assigned to point to the same object as b2 then the original object that b1 pointed to is not reachable by any code.

Questions

Question 1)

Which of the following is the correct syntax for suggesting that the JVM performs garbage collection?

1) System.free();
2) System.setGarbageCollection();
3) System.out.gc();
4) System.gc();

Question 2)

What code can you write to ensure that the Integer objects are garbage collected at a particular point in this code?

public class Rub{
        Integer  i= new Integer(1);
        Integer  j=new Integer(2);
        Integer k=new Integer(3);
public static void main(String argv[]){
        Rub r = new Rub();
        r.amethod();
    }

    public void amethod(){
    System.out.println(i);
    System.out.println(j);
    System.out.println(k);
    }
}

1) System.gc();
2) System.free();
3) Set the value of each int to null
4) None of the above

Question 3)

Which of the following statements are true?

1)You cannot be certain at what point Garbage collection will occur
2) Once an object is unreachable it will be garbage collected
3) Both references and primitives are subject to garbage collection.
3) Garbage collection ensures programs will never run out of memory

Question 4)

At what point will the object created on line 8 be eligible for garbage collection?

public class RJMould{
    StringBuffer sb;
    public static void main(String argv[]){
   RJMould rjm = new RJMould();
   rjm.kansas();
   }
    public void kansas(){
   sb = new StringBuffer("Manchester");
   StringBuffer sb2 = sb;
   StringBuffer sb3 = new StringBuffer("Chester");
   sb=sb3;
   sb3=null;
   sb2=null;
    }
}



1) Line 11
2) Line 9
3) Line 12
4) Line 13

Question 5)

Which of the following statements are true?

1) finalize will always run before an object is garbage collected
2) finalize may run before or after an object is garbage collected
3) finalize will run when an object becomes unreachable
4) finalize allows a programmer to free memory allocated to an object



Answers

Answer to Question 1)

4) System.gc();

Answer to Question 2)

4) None of the above

You can only suggest garbage collection, therefore you cannot be certain that it will run at any particular point in your code. Note that only instances of classes are subject to garbage collection not primitives.

Answer to Question 3)

1) You cannot be certain at what point Garbage collection will occur

Once an object is unreachable it will be subject to garbage collection but you cannot be certain it ever will actually be garbage collected. The garbage collection mechanism only applies to objects not primitives. You should be able to guess that garbage collection cannot ensure programs do not run ever run out of memory, but it does ensure that memory no longer required is reallocated to be available.

Answer to Question 4)

4) Line 13

On line 9 the object created on line 8 has the reference sb2 pointed to it. Until something happens to make that reference unable to reach the object it will not be eligible for garbage collection.

Answer to Question 5)

Which of the following statements are true?

1) finalize will always run before an object is garbage collected
2) finalize may run before or after an object is garbage collected
3) finalize will run when an object becomes unreachable
4) finalize allows a programmer to free memory allocated to an object

Finalize will always be run before an object is garbage collected. It cannot run after it is collected because by then the object will cease to exit. When an object becomes unreachable it will be eligible for garbage collection but there is no guarantee when finalize will run, only that it will run before garbage collection happens. The final option is a passable description of destructors in C++ but not of the finalize method in Java.




Other sources on this topic

An article from Sun
http://developer.java.sun.com/developer/technicalArticles/ALT/RefObj/index.html

Jyothi Krishnan on this topic at
http://www.geocities.com/SiliconValley/Network/3693/obj_sec3.html#obj8

Artima.com
http://www.artima.com/insidejvm/ed2/gc.html
http://www.artima.com/underthehood/gc.html

From Sun
http://java.sun.com/docs/books/performance/1st_edition/html/JPAppGC.fm.html#998394

Jane Gritsci
http://www.janeg.ca/scjp/gc/finalize.html








Previous
Index

Next