TODAY JAVA SCHOOL

In java school, programming, design, computer general knowledge, web application, software, web services, social media, digital marketing, oops, concept of programming language, oops feature, console media, graphics medium, first programming, c, c ++ , Java, PHP, SQL, MySQL, HTML, HTML_5, J_query, JavaScript, Bootstrap, Framework, images with logos, examples, shared and explained.

https://www.amazon.in/b?node=26373545031&linkCode=ll2&tag=1234567801cdb-21&linkId=3b9882431b00409b44141e0344b35a15&language=en_IN&ref_=as_li_ss_tl

Breaking

Tuesday, 28 April 2020

Java Garbage Collection | Java Garbage Collection Example | Java Garbage Collection Type

        Java Garbage Collection

In java, garbage means unreferenced objects.

Garbage Collection is process of reclaiming the runtime unused memory automatically. In other words, it is a way to destroy the unused objects.

To do so, we were using free() function in C language and delete() in C++. But, in java it is performed automatically. So, java provides better memory management.

example java garbage collection
Fig: Java Garbage Collection



Advantage of Garbage Collection

o    It makes java memory efficient because garbage collector removes the unreferenced objects from heap memory.
o    It is automatically done by the garbage collector(a part of JVM) so we don't need to make extra efforts.

 

How can an object be unreferenced?

example unreferenced object

Fig: Unreferenced Object 

There are many ways:
  • By nulling the reference
  • By assigning a reference to another
  • By anonymous object etc.

 

  1) By nulling a reference:

      
       Employee e=new Employee();  
       e=null;  

 

2) By assigning a reference to another: 

Employee e1=new Employee();
    Employee e2=new Employee();  
  e1=e2;//now the first object referred by e1 is available for garbage collection  

3) By anonymous object:

    new Employee();  

 

finalize() method

The finalize() method is invoked each time before the object is garbage collected. This method can be used to perform cleanup processing. This method is defined in Object class as:
     protected void finalize(){}  

gc() method

The gc() method is used to invoke the garbage collector to perform cleanup processing. The gc() is found in System and Runtime classes.
      public static void gc(){} 


Simple Example of garbage collection in java

    public class TestGarbage1{  
    public void finalize(){System.out.println("object is garbage collected");}  
    public static void main(String args[]){  
   TestGarbage1 s1=new TestGarbage1();  
   TestGarbage1 s2=new TestGarbage1();  
   s1=null;  
   s2=null;  
   System.gc();  
  }  
    }  

Output:

       object is garbage collected
       object is garbage collected

No comments:

Post a Comment