Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Java_19_Garbage

Uploaded by

abhinavrajnair
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Java_19_Garbage

Uploaded by

abhinavrajnair
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

1.

Garbage Collection in Java:


• Garbage collection in Java is the process by which Java programs perform
automatic memory management. Java programs compile to bytecode that can be
run on a Java Virtual Machine, or JVM for short. When Java programs run on the
JVM, objects are created on the heap, which is a portion of memory dedicated to
the program. Eventually, some objects will no longer be needed. The garbage
collector finds these unused objects and deletes them to free up memory.
• Garbage Collection is process of reclaiming the runtime unused memory
automatically.
• 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.
Advantage of Garbage Collection
•It makes java memory efficient because garbage collector removes the unreferenced
objects from heap memory.
•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?


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(){}

Note: The Garbage collector of JVM collects only those objects that are created by
new keyword. So if you have created any object without new, you can use finalize
method to perform cleanup processing (destroying remaining objects).

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(){}

Note: Garbage collection is performed by a daemon thread called Garbage


Collector(GC). This thread calls the finalize() method before object is garbage
collected.
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
Real-World Example
Let’s take a real-life example, where we use the concept of the garbage collector.
Question: Suppose you go for the internship at GeeksForGeeks, and you were
told to write a program to count the number of employees working in the
company(excluding interns). To make this program, you have to use the concept of
a garbage collector.
This is the actual task you were given at the company:
Write a program to create a class called Employee having the following data
members.
1. An ID for storing unique id allocated to every employee.
2. Name of employee.
3. age of an employee.
Also, provide the following methods:
1.A parameterized constructor to initialize name and age. The ID should be
initialized in this constructor.
2.A method show() to display ID, name, and age.
3.A method showNextId() to display the ID of the next employee.
Now any beginner, who doesn’t know Garbage Collector in Java will code like this:
// Java Program to count number
// of employees working
// in a company
class Employee {

private int ID;


private String name;
private int age;
private static int nextId = 1;
// it is made static because it
// is keep common among all and
// shared by all objects

public Employee(String name, int age)


{
this.name = name;
this.age = age;
this.ID = nextId++;
}
public void show()
{
System.out.println("Id=" + ID + "\nName=" + name + "\nAge=" + age);
}
public void showNextId()
{
System.out.println("Next employee id will be="
+ nextId);
}
}
class UseEmployee {
public static void main(String[] args)
{
Employee E = new Employee("GFG1", 56);
Employee F = new Employee("GFG2", 45);
Employee G = new Employee("GFG3", 25);
E.show();
F.show();
G.show();
E.showNextId();
F.showNextId();
G.showNextId();

{ // It is sub block to keep


// all those interns.
Employee X = new Employee("GFG4", 23);
Employee Y = new Employee("GFG5", 21);
X.show();
Y.show();
X.showNextId();
Y.showNextId();
}
// After countering this brace, X and Y
// will be removed.Therefore,
// now it should show nextId as 4.
// Output of this line
E.showNextId();
// should be 4 but it will give 6 as output.
}
}
Now to get the correct output:
Output
Now garbage collector(gc) will see 2
Id=1
objects free. Now to decrement
Name=GFG1
nextId,gc(garbage collector) will call
Age=56
method to finalize() only when we
Id=2
programmers have overridden it in our
Name=GFG2
class. And as mentioned previously, we
Age=45
have to request gc(garbage collector), and
Id=3
for this, we have to write the following 3
Name=GFG3
steps before closing brace of sub-block.
Age=25
1.Set references to null(i.e X = Y = null;)
Next employee id will be=4
2.Call, System.gc();
Next employee id will be=4
3.Call, System.runFinalization();
Next employee id will be=4
Now the correct code for counting the
Id=4
number of employees(excluding interns)
Name=GFG4
Age=23
Id=5
Name=GFG5
Age=21
Next employee id will be=6
Next employee id will be=6
Next employee id will be=6
// Correct code to count number
// of employees excluding interns.

class Employee {

private int ID;


private String name;
private int age;
private static int nextId = 1;

// it is made static because it


// is keep common among all and
// shared by all objects
public Employee(String name, int age)
{
this.name = name;
this.age = age;
this.ID = nextId++;
}
public void show()
{
System.out.println("Id=" + ID + "\nName=" + name
+ "\nAge=" + age);
}
public void showNextId()
{
System.out.println("Next employee id will be="+ nextId);
}
protected void finalize()
{
--nextId;
// In this case,
// gc will call finalize()
// for 2 times for 2 objects.
}
}
public class UseEmployee {
public static void main(String[] args)
{
Employee E = new Employee("GFG1", 56);
Employee F = new Employee("GFG2", 45);
Employee G = new Employee("GFG3", 25);
E.show();
F.show();
G.show();
E.showNextId();
F.showNextId();
G.showNextId();
{
// It is sub block to keep
// all those interns.
Employee X = new Employee("GFG4", 23);
Employee Y = new Employee("GFG5", 21);
X.show();
Y.show();
X.showNextId();
Y.showNextId();
X = Y = null;
System.gc();
System.runFinalization();
}
E.showNextId();
}
}
Output

Id=1
Name=GFG1
Age=56
Id=2
Name=GFG2
Age=45
Id=3
Name=GFG3
Age=25
Next employee id will be=4
Next employee id will be=4
Next employee id will be=4
Id=4
Name=GFG4
Age=23
Id=5
Name=GFG5
Age=21
Next employee id will be=6
Next employee id will be=6
Next employee id will be=4

You might also like