Hi, Please CORRECT / SUPPLEMENT my understanding of garbage collection(GC) in Java.
A "new" statement allocates memory for an object and associates the memory with the variable name provided . Example : Integer I =new Integer(); Java has a mechanism called Garbage collection(GC) which is a separate thread that is activated when the program needs it , to release unused memory of objects of that program . When GC releases memory of an object , that object ceases to exist and trying to access that object is not possible once its memory is released . If the finalize method is provided for an object , at the time of GC of that object ,finalize method of that object is run first before destroying that object .
Assigning an object to null , makes it eligible for gc . But if references to that object still exist , then the object will not be garbage collected .
Please take a look at this example code from "Thinking in Java"
In this code , the number of created and finalised objects is just a trade-off between the available memory space for the program and the speed of execution of both threads (main and garbage collection). So once the program faces memory shortage , the GC is kicked off and it keeps on erasing obj 1,2,3 ...etc from memory . Do pour in your views ! Thanks, Jenny
Hi Jenny, I guess you cannot specify when the garbage collection thread will do its job. Just that an object becomes eligible for garbage collection doesn't mean it is immediately collected. Ijust wanted to add this point Shree
Another point to take into consideration... The GC isn't going to come around just because your program needs memory. The GC thread runs whenever the CPU has no threads of a higher priority in the pool....the GC cometh last!!
Lori Battey<br />SCJP2
You showed up just in time for the waffles! And this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop