Saturday, July 11, 2015

Garbage Collection in Java

·         objects are created on heap area in Java  irrespective of their scope e.g. local or member variable.
·         Garbage collection is a mechanism provided by Java Virtual Machine to reclaim heap space from objects which are eligible for Garbage collection.
·         Garbage collection relieves java programmer from memory management which is essential part of C++ programming and gives more time to focus on business logic.
·         Garbage collector works on Mark and Sweep algorithm and is lineant in its operation.
·         Garbage Collection in Java is carried by a daemon thread called Garbage Collector.
(daemon=background)
·         Before removing an object from memory Garbage collection thread invokes finalize () method of that object and gives an opportunity to perform any sort of cleanup required.
·         You as Java programmer can not force Garbage collection in Java; it will only trigger if JVM thinks it needs a garbage collection based on Java heap size.
·         There are methods like System.gc () and Runtime.gc () which is used to send request of Garbage collection to JVM but it’s not guaranteed that garbage collection will happen.
·         JVM supports many different implementations of Garbage collectors.. Many are bundled into J2SE also. An application may choose the GC according to the needs (In case of advance programming needs).
·         One thing is assured, that before the Garbage Collector reclaims and object and releases its memore, it will invoke the protected method finalize() on the object. This method is invoked only once on an object during its life time and that too at the end of life time.


Since Garbage Collection is automatic in Java, memory management errors get reduced in java which may occur in case of manual memory allocation and de-allocation. Allocation part is take care of by constructors in java and de-allocation by Garbage Collector, thereby automating the memory mgmt. in java completely.

No comments:

Post a Comment