Garbage Collection
Garbage Collection
Objects dynamically allocated from a pool of free memory using new operator Possible for new to fail insufficient memory Key: Recovery of free memory from unused objects, making memory available for subsequent reallocation
When no reference to an object exists, that object is assumed to be no longer used and memory occupied by object is recycled
Occurs only sporadically during execution of a program It will not occur simply because one or more objects exist that are no longer used
Before an object is removed by garbage collection, finalize() method is invoked to give it a last opportunity to clean up its act and free other kind of resources it may hold
e.g. closing files , terminating network connections , non window resources ensures that object terminates cleanly
finalize() method is called once and only once before the object is garbage collected
No guarantee when this will happen may never run on a system that is not short of memory Finalization and Collection occur in two distinct phases of garbage collection process First items are finalized and then collected
Syntax
protected void finalize() { //finalization code here }
protected: access specifier that prevents access to finalize() by code defined outside its class
class Finalize { public static void main(String args[]) { int count; FDemo ob = new FDemo(o); for (count = 1 ; count < 100000; count++) ob.generator(count); } }
Sometimes a method will need to refer to object that invoked it this keyword When a method is called it is automatically passed an implicit argument that is reference to invoking object. Reference is called this.
class Point extends Object { public double x ; public double y; Point() { x = 0.0; y = 0.0; }