Garbage Collection


In this Magercise, you learn about using the scrapbook for testing small Java code fragments. You will also examine how Java deallocates memory for you automatically (how its garbage collector tracks and frees objects that are no longer needed).

We have provided a class called EchoObject that prints out a message, which is set during object creation, to standard out when the object is garbage collected by the system (that is, when the garbage collector frees the memory). The finalize method is a Java method that is called by the garbage collector right before it is deleted. Class EchoObject looks like:

class EchoObject {
        private String finalWords = "Goodbye, cruel World!";
        public EchoObject() {
		// use the default value of finalWords.
        }
	public EchoObject (String dyingWords) {
	        finalWords = dyingWords;
	}
        public void finalize() {
                System.out.println(finalWords);
        }
}

You will be entering a code fragment that creates two of these objects and then you will wait to see the garbage collector call method finalize before it frees the memory. You will not make any explicit calls to finalize.

Tasks

Perform the following tasks:

  1. Select "Console" from the "Window" menu to bring up the window that displays standard output. Select "Scrapbook" from the "Window" menu also. The scrapbook can be used to enter and test small code fragments easily and quickly. Orient the two windows so that you can see both easily.

  2. From the "Page" menu, select "Run in...", which allows us to set the context under which our code fragment will run. Because we want the code fragment to know about EchoObject, type in "EchoObject" in the top text field when the dialog box appears. Click OK.

  3. Enter the following text into the visible text area:
    EchoObject a,b;
    a = new EchoObject("bye");
    b = new EchoObject("die");
    System.out.println("done");
    

    Your scrapbook should look like this:

    Select the entire four lines of code and, from the popup menu (obtained by right mouse clicking), select "Run". Shortly, you should see "done" appear in the standard output pane of the console.

  4. Not immediately, but when VisualAge decides to run the garbage collector, you will see "bye" and "die" appear in the standard output pane of the console. The delay is usually less than a minute.
    The console will look similar to the following.

    The key ideas to note are that you do not have to collect your own garbage and, consequently, you do not have control over when the system collects your garbage nor in what order the objects are collected. In C or C++, you would have to call free() or delete on the data elements manually.

The task numbers above are linked to the step-by-step help page. Also available is a complete solution to the problem, and expected behavior, to demonstrate it.

Copyright © 1996-1997 MageLang Institute. All Rights Reserved.