Garbage Collection

8) State the behavior that is guaranteed by the garbage collection system and write code that explicitly makes objects eligible for collection.
java -noasyncgc .....

Note: If you do this, it is almost gauranteed to fail with memory exhaustion at some point. It can be used only to experiment the performance difference it makes.

System.gc();

to run garbage collector at any point you choose. (doesn't mean you will get it)

public void method() {
BigObject bo = new BigObject(2000);
//do something
//let the runtime environment know that "bo" is no longer needed
bo = null;
}
//do some processing

The runtime environment could collect the "BigObject" anytime after "bo" is set to null. Setting the reference to null doesn't guarantee that the object will be garbage collected quickly, but it does help.

In the exam point of view : eg,
1. obj = new Jo();
2. obj.doSomething();
3. obj = new Jo(); //Same as obj=null;
4. obj.doSomething();
The object referred by obj in line 1 becomes eligible for gc at line 4 ( anytime after line 3 has been executed).
another eg,
Aclass a = new Aclass(); // Object 1
Aclass b= new Aclass(); // Object 2
Aclass c = new Aclass(); // Object 3
a=b; // now we have no valid object reference to object "a" and it will be
// garbage collected sometime after this statement. But when?......
a=c;
c=null; // no garbage collection will be eligible since
// "a" still refers to Object 3
a=null; // now object "c" is eligible for gc since it always had a valid reference.
// Should "b" go out of scope; then we would possibly have eligibility for gc.
// there might still be other references to object "b" preventing the collection.
eg by Kathy,
public class Test extends Applet {

int a=3;
String b="jo"; // call this object1
String c=b; // two references to object1
Object d=new Object(); // object2
public void init() {
methodA(b); // pass a copy of a reference to Object1
methodB(d); // pass a copy of a reference to Object2
a=5;
}
void methodA(String b) { // a new local var b, with a ref to Object 1
b=c; // local b directed to Object1 (copy of c ref)
c=null; // c no longer ref object1
} // local b goes out of scope but instance var b still refers object1
void methodB(Object o) { // a new local var o with a ref to object2 d=new Object(); // HERE IT IS! d no longer refer to Object2
} // local o goes out of scope so no more ref to object2
}


Remember: You can suggest Garbage Collection, but no gaurantee that it will ever happen.




Copyright © 1999-2000, Jyothi Krishnan
All Rights Reserved.