Responsive Ads Here

Wednesday, May 29, 2013

Gargbage Collection (GC)

What is Garbage Collection (GC)?

• The Java virtual machine's heap stores all objects created by a running Java application.
• Objects are created by the program through new keyword, but never freed explicitly by the program
          > No need to call free().
• Garbage collection is the process of automatically freeing objects that are no longer needed
• An object is determined to be “no longer needed” when there is no other object referencing to it
         > Each object has a reference counter - when it becomes 0, it means there is no other object referencing to it


Why Garbage Collection (GC)?

Advantages of GC

• Programmer is free from memory management
        > Less error prone code
• System cannot crash due to memory management
        > More reliable application
        > Memory-leak is still possible, however - you can use memory profiler to find out where memory-leaking code is located

Disadvantages of GC

• GC could add overhead
       > Many GC schemes are focused on minimizing GC overhead
• GC can occur in an non-deterministic way

       > Real-time Java addresses this

When and How Garbage Collection (GC) Occur?

• JVM performs GC when it determines the amount of free heap space is below a threshold

        > This threshold can be set when a Java application is run

How Does JVM Perform GC?

• The garbage collector must somehow determine which objects are no longer referenced and make available the heap space occupied by such unreferenced objects.
• The simplest and most crude scheme is to keep reference counter to each object

• There are many different schemes - years of research


Java API

GC Related Java API

• finalize() method in Object class
        > Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.
• gc() method in System class
        > Runs the garbage collector.
        > Calling the gc method suggests that the Java Virtual Machine expend effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse.
        > When control returns from the method call, the Java Virtual Machine has made

No comments:

Post a Comment