0% found this document useful (0 votes)
5 views19 pages

GarbageCollections

The document discusses garbage collection in Java, explaining how it differs from C++ where developers manage object destruction. It outlines approaches to make objects eligible for garbage collection, methods to request garbage collection, and the role of the finalize() method. Additionally, it covers the Java Heap Memory structure and the behavior of the Garbage Collector in managing memory efficiently.

Uploaded by

Rakesh kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views19 pages

GarbageCollections

The document discusses garbage collection in Java, explaining how it differs from C++ where developers manage object destruction. It outlines approaches to make objects eligible for garbage collection, methods to request garbage collection, and the role of the finalize() method. Additionally, it covers the Java Heap Memory structure and the behavior of the Garbage Collector in managing memory efficiently.

Uploaded by

Rakesh kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

● Introduction

● Approaches to make an Object Eligible for Garbage Collection


● Approaches for requesting garbage Collector to Run Garbage
Collector
● Finalization
● Java Heap Memory and its Memory Areas
● Garbage collection in Young Generation
● Garbage collection in Old Generation
● Types of Garbage Collectors for Old generation

Garbage Collection:
—----------------
In C++ programming language Developers are responsible for creating
objects and destroying objects. If Developers are not destroying
objects then we are able to get the following problems.
1. Memory is full with the present application objects, no memory
for the next application objects.
2. No security for the data.

In Java , Developers are responsible for creating objects only,


Developers are not responsible for Destroying objects.

In Java applications, to destroy objects JAVA has provided an internal


component inside the JVM that is “Garbage Collector”.

In Java applications, when Heap memory is full then the Garbage


Collector will destroy the useless objects.

IN Java applications, when the application execution is completed ,


automatically Garbage Collector will destroy objects.

In Java applications, JAVA has provided a process for the developers


to destroy the objects explicitly as per the requirement.

Even though a programmer is not responsible for destruction of


objects, it is always a good programming practice to make an object
eligible for GC if it is no longer required.

An object is eligible for GC if and only if it does not have any


references.

If we want to destroy an object in java applications then we have to


use the following steps.
1. Make Eligible an object for the Garbage Collection:
—-----------------------------------------------
To make an object eligible for the Garbage Collection we have to
assign null value to the reference variable.
A a = new A();
a = null;

2. Activate Garbage Collector to destroy objects:


—----------------------------------------
To activate Garbage Collector to destroy objects we have to use
the following method.

System.gc();

When we access the System.gc() method , internally JVM will


access the finalize() method just before destroying the object.

EX:
class A{
A(){
System.out.println("Object Creating.....");
}

@Override
protected void finalize() throws Throwable {
System.out.println("Object Destroying......");
}
}
public class Main {
public static void main(String[] args) {
A a = new A();
a = null;
System.gc();
}
}

Object Creating.....
Object Destroying......

Approaches to make an object eligible for Garbage Collection:


—-------------------------------------------------------------
1. Assign null value to the reference variable.
—-----------------------------------------
If an object is no longer required then we can make eligible for
GC by assigning “null” to all its reference variables.
EX:
Student std1=new Student();
Student std2=new Student();
-----
-----
std1=null;
std2=null;
-----
-----
EX:
class A{
A(){
System.out.println("Object Creating.....");
}

@Override
protected void finalize() throws Throwable {
System.out.println("Object Destroying......");
}
}
public class Main {
public static void main(String[] args) {
A a1 = new A();
a1 = null;
A a2 = new A();
a2 = null;
System.gc();
}
}

Object Creating.....
Object Creating.....
Object Destroying......
Object Destroying......

2. Reassign the reference variables:


—-----------------------------
If assign one reference variable to another reference variable
then the reference variable which refers to the previous object
is eligible for Garbage Collection.
EX:
Student std1 = new Student();
Student std2 = new Student();
---
---
std1 = new Student();
----
----
std2=std1;
---
----

EX:
class A{
A(){
System.out.println("Object Creating.....");
}

@Override
protected void finalize() throws Throwable {
System.out.println("Object Destroying......");
}
}
public class Main {
public static void main(String[] args) {
A a1 = new A();
A a2 = new A();
a1 = a2;
System.gc();

}
}

Object Creating.....
Object Creating.....
Object Destroying......
3. Creating Object inside the Methods:
—--------------------------------
If we provide an Object creation statement inside the methods
then JVM will create an object when the respective method is
executed, when method execution is completed , automatically the
object which we have created inside the method is eligible for
Garbage Collection.
EX:
class Test{
psvm(String[] args){
m1();
}
static void m1(){
Student st1 = new Student();
Student st2 = new Student();
}
}
EX:
class A{
A(){
System.out.println("A Class Object Creating....");
}
public void finalize(){
System.out.println("A class Object Destroying.....");
}
}
class B{
void m1(){
A a = new A();
}
}
public class Main {
public static void main(String[] args) {
B b = new B();
b.m1();
System.gc();
}
}

A Class Object Creating....


A class Object Destroying.....

EX:

EX:
class A{
A(){
System.out.println("Object Creating....");
}

@Override
protected void finalize() throws Throwable {
System.out.println("Object Destroying.....");
}
}
class B{
A getA(){
A a = new A();
return a;
}
}
public class Main {
public static void main(String[] args) {
B b = new B();
A a1 = b.getA();
System.gc();
}
}
Object Creating....

Island of Isolation:
—----------------
If objects are not having explicit references or the Objects are
having internal references are eligible for GC.
EX:
class Test{
Test t;
psvm(String[] args){
Test t1 = new Test();
Test t2 = new Test();
Test t3 = new Test();

t1.t=t2;
t2.t=t3;
t3.t=t1;

t1=null; //No Object is eligible for GC.


t2=null; //No Object is eligible for GC.
t3=null; //All Objects are eligible for GC, bcz, all
Explicit references are nullified.
}
}

Approach to activate Garbage Collector and to request Garbage


Collector about the Object Destruction:
—---------------------------------------------------------------------
-------
In Java applications, when we make an object eligible for Garbage
Collection then the Garbage Collection may destroy the objects
immediately or may not destroy the objects immediately , there is no
guarantee to destroy the objects immediately, but in maximum cases
Garbage Collector will destroy objects immediately.
****************************** OR ****************************
Once we make an object eligible for GC it may not be destroyed
immediately by the GC. Whenever a JVM runs GC then only objects will
be destroyed by the GC. But when exactly JVM runs GC we can’t expect,
it is vendor dependent.
We can request JVM to run Garbage collector programmatically, but
whether JVM accepts our request or not there is no guarantee. But most
of the time JVM will accept our request.

If we want to request a Garbage Collector to destroy objects then we


have to use the following approaches.

1. By Using the static gc() method from System class:


System.gc();

2. By Using non static method gc() method from Runtime class:


Runtime rt = Runtime.getRuntime();
rt.gc();

EX:
class A{
A(){
System.out.println("Object Creating....");
}

@Override
protected void finalize() throws Throwable {
System.out.println("Object Destroying.....");
}
}
class B{
A getA(){
A a = new A();
return a;
}
}
public class Main {
public static void main(String[] args) {
B b = new B();
b.getA();
Runtime runtime = Runtime.getRuntime();
runtime.gc();
}
}

Object Creating....
Object Destroying.....

Overview of Runtime Class:


—--------------------
A Java application can communicate with JVM by using a Runtime
object. Runtime class is a singleton class present in
java.lang.Package.
We can create a Runtime object by using factory method
getRuntime().

EX: Runtime r = Runtime.getRuntime();

Once we get a Runtime Object we can call the following methods on


that object.
freeMemory(): returns the free memory present in the heap.
totalMemory(): returns total memory of the heap.
gc(): for requesting JVM to run gc.

EX:
import java.util.Date;
class RuntimeDemo{
public static void main(String args[])
{
Runtime r = Runtime.getRuntime();
System.out.println(“total memory of the heap:”+
r.totalMemory());
System.out.println(“free memory of the heap:”+
r.freeMemory());
for(int i=0; i<10000; i++){
Date d = new Date();
d = null;
}
System.out.println(“free memory of the
heap:”+r.freeMemory());
r.gc();
System.out.println(“free memory of the
heap:”+r.freeMemory());
}
}
OUTPUT:
—---
Total memory of the heap: 5177344
Free memory of the heap: 4994920
Free memory of the heap: 4743408
Free memory of the heap: 5049776

Note: Runtime class is a singleton class so do not create the


object to use constructor.

Q)Find the valid method calls for gc()?


—----------------------------------------
1. System.gc(); —-----> Valid
2. Runtime.gc(); —-----> Invalid
3. Runtime.getRuntime().gc(); —--> Valid
4. (new Runtime()).gc(); —-----> Invalid

NOTE: gc() method present in System class is static, whereas it is an


instance method in Runtime class. Over Runtime class gc() method,
System class gc() method is recommended to use. In java, it is not
possible to find the size of an object and address of an object.

finalize() method:
—-----------------
The main intention of finalize() method is
1. To give final intimation about destroying an object.
2. To perform cleanup operations just before destroying an Object.

IN Java applications, the finalize() method will be executed by JVM


automatically when we destroy an object (If the corresponding class
contains the finalize() method then it will be executed otherwise the
Object class finalize() method will be executed.).

In Java, finalize() method was declared in the java.lang.Object class


like below.

protected void finalize()throws Throwable

EX:
class A{

public void finalize(){


System.out.println("finalize()....");
}
}
public class Main {
public static void main(String[] args) {
A a = new A();
a = null;
System.gc();
}
}

EX:

public class Main {


@Override
protected void finalize() throws Throwable {
System.out.println("finalize()-Test");
}

public static void main(String[] args) {


String str = new String("Durgasoft");
str = null;
System.gc();
}
}

Status: No Output.

In the above example, the String class object is eligible for Garbage
Collection, so the String class finalize() method will be executed,
not the Main class finalize() method.

EX:

public class Main {


@Override
protected void finalize() throws Throwable {
System.out.println("finalize()-Test");
}

public static void main(String[] args) {


String str = new String("Durgasoft");
Main m = new Main();
m = null;
System.gc();
}
}

Case 1:
—---
Just before destroying any object, GC always calls the finalize()
method on the Object which is eligible for GC then the corresponding
class finalize() method will be executed.
For Example, if a String object is eligible for GC then the String
class finalize() method is executed but not Test class finalize()
method.

EX:
class Test{
psvm(){
String s = new String(“Durga Software Solutions”);
Test t = new Test();
s = null;
System.gc();
System.out.println(“End of Main”);
}
public void finalize(){
System.out.println(“finalize() method is executed”);
}
}
OUTPUT: End of Main
In the above program the String class finalize() method got executed
which has Empty implementation.
If we replace String object with Test object then Test class
finalize() method will be executed.

The following program is an Example of this.


class Test{
psvm(){
String s = new String(“Durga Software Solutions”);
Test t = new Test();
t = null;
System.gc();
Sop(“finalize() method is executed”);
}
}
OUTPUT: finalize() method is executed.
End of Main
Case 2
—----
We can call the finalize() method explicitly then it will be executed
just like a normal method call and the object won’t be destroyed. But
before destroying any object GC always calls the finalize() method.

EX:
class Test{
psvm(){
Test t = new Test();
t.finalize();
t.finalize();
t=null;
System.gc();
sop(“End of Main.”);
}
public void finalize(){
sop(“finalize() method called”);
}
}
OUTPUT:
finalize() method called.
finalize() method called.
finalize() method called.
End of Main.
In the above program the finalize() method got executed 3 times in
that 2 times explicitly by the programmer and one time by the gc.

Case 3
—----
finalize() method can be call either by the programmer or by the GC.
If the programmer explicitly calls the finalize() method and while
executing the finalize() method if an exception is raised and uncaught
then the program will be terminated abnormally.

If GC calls the finalize() method and while executing the finalize()


method if an exception is raised and uncaught then JVM simply ignores
that exception and the program will be terminated normally.

class Test{
psvm(){
Test t = new Test();
//t.finalize();-------line(1)
t=null;
System.gc();
sop(“End of main.”);
}
public void finalize(){
sop(“finalize() method called”);
sop(10/0);
}
}
If we do not comment line 1 then the programmer calling finalize()
method explicitly and while executing the finalize() method
ArithmeticException raised which is uncaught hence the program
terminated abnormally.

If we comment line 1 then GC calls finalize() method and JVM ignores


ArithmeticException and the program will be terminated normally.

Which of the following is true?


—---------------------------
While executing finalize() method JVM ignores every exception(invalid)
While executing finalize() method JVM ignores only uncaught
exception(valid)

Case 4:
—----
On any Object, GC calls finalize() method only once.

EX:
class FinalizeDemo{
static FinalizeDemo s;
psvm(String s[])throws Exception{
FinalizeDemo f = new FinalizeDemo();
sop(f.hashCode());
f=null;
System.gc();
Thread.sleep(5000);
sop(s.hashCode());
s=null;
System.gc();
Thread.sleep(5000);
sop(“End of main thread”);
}
public void finalize(){
sop(“finalize method called”);
s = this;
}
}
OUTPUT:
D:\Enum>java FinalizeDemo
4072869
Finalize method called
4072869
End of main method.

Note:
—---
The behaviour of the GC is vendor dependent and varies from JVM to JVM
hence we can’t predict the exact answer for the following.
● What is the algorithm followed by GC.
● Exactly at what time JVM runs GC.
● In which order GC identifies the eligible objects.
● In which order GC destroys the object etc.
● Whether GC destroys all eligible objects or not.

Whenever the program runs with low memory then JVM runs GC, but we
can’t predict exactly at what time.

Q) In Java applications, if we access the finalize() method explicitly


like a normal Java method , will GarbageCollector destroy the
respective object?
—---------------------------------------------------------------------
----
Ans:
—----
No, if we access finalize() method explicitly then JVM will execute
finalize() method like a normal java method , not as per Garbage
Collection, when JVM access finalize() method automatically then JVM
will perform garbage Collection.

EX:
class A{
@Override
protected void finalize() throws Throwable {
System.out.println("finalize()-A");
}
void m1(){
System.out.println("m1-A");
}
}
public class Main {
public static void main(String[] args)throws Throwable {
A a = new A();
a.finalize();
a.m1();
}
}

finalize()-A
m1-A

EX:
class A{
@Override
protected void finalize() throws Throwable {
System.out.println("finalize()-A");
}

}
public class Main {
public static void main(String[] args)throws Throwable {
A a = new A();
a = null;
System.gc();
System.gc();
System.gc();
}
}

finalize()-A

Q)What is memory Leak?


—----------------------
Ans:
—---
In Java applications, if any object is available without using it in
the application and which is not eligible for Garbage Collection then
that object is called a Memory Leak.

If More number of memory leaks are identified in the java applications


automatically JVM is able to raise an exception like
OutofMemoryException, we are not having any solution explicitly ,we
have to cache those objects by using third party cache mechanisms.

Heap Memory Structure:


—-------------------
Heap memory is mainly divided into the following two parts.
1. Young Generation
● Eden Space
● Survivor Space
Survivor Space
Survivor Space
2. Old Generation

When we create an object newly, that object will come to Young


Generation, in Young Generation, that Object will come to Eden Space,
at Eden space Minor Garbage Collection will be performed, if any
object is dereference object then Minor Garbage Collection will remove
that object. In Eden Space, if any object is still live then Garbage
Collector will move that live objects to Survivor space, in Survivor
space , initial objects will come to S0 survivor space, there also
Minor Garbage Collection will be performed, where if any object is
dereferenced then Garbage Collector will remove that objects and the
remaining objects are moved to S1 Survivor space, there again Minor
Garbage Collection is going on, still any object is live then that
object will be moved to Old Generation. In the Old Generation, Major
Garbage Collection will be performed.

In the Old Generation, we will perform Garbage Collection by using


either of the following Garbage Collectors.
● Serial Garbage Collector
● Parallel Garbage Collector
● Parallel Old Garbage Collector
● Concurrent Mark and Sweep [CMS] Garbage Collector
● Garbage First [G1] Garbage Collector

Serial Garbage Collector:


—---------------------
This Garbage Collector will follow the following algorithm.
● Mark the Surviving objects in the Old Generation.
● Keep all marked objects at the front end of the Heap and keep all
the unmarked Objects at another end [Sweep].
● Free the memory for unmarked objects [Compact]

It will perform Garbage Collection by using Single Thread.


● While performing garbage Collection, it will pause all
application threads which are running in java applications.
● It is suitable for Single Thread Model.
● It is not suitable for multi threaded applications.
● It is suitable for Standalone applications.
● It is not suitable for Server side applications.
● To run this Garbage Collector, it will take less memory.
● To activate this Garbage Collector we have to use the following
Command. D:\java9>java -XX:+UseSerialGC Test

Parallel Garbage Collector / Throughput Garbage Collector:


—------------------------------------------------------
1. It will use the following algorithm to perform Garbage
Collection.
● Mark the Surviving objects in the Old Generation.
● Keep all marked objects at front end of the Heap and keep
all the unmarked Objects at another end [Sweep]
● Free the memory for unmarked objects [Compact]

2. It is the default Garbage Collector in JVM.


3. It will use more than one thread to perform garbage Collection.
4. It will be used in a Multi Threaded Environment.
5. It is suitable in Server side programming
6. It will pause all the threads while performing Garbage Collection
7. It requires more memory to perform garbage Collection when
compared with Serial Garbage Collector.
8. To activate this Garbage Collector we will use the following
command. D:\java9>java -XX:+UseParallelGC Test

Parallel Old Garbage Collector:


—---------------------------
1. It was introduced in the JDK5.0 version.
2. It is the same as Parallel Garbage Collector, but it will use the
"Mark-Summary-Compact" Algorithm.
● Mark Survivor objects in the Old Generation.
● Identifies all Survivor objects from the areas where
Garbage Collection was performed previously.
● Delete Unmarked Objects, that is, Compact.
3. To activate this Garbage Collector we have to use the following
command. D:\java9>java -XX:+UseParallelOldGC Test

Concurrent Mark And Sweep [CMS] Garbage Collector:


—----------------------------------------------
1. It allows multiple threads to perform garbage Collection.
2. It will not freeze all the application threads while performing
Garbage Collection except in the following two situations.
● While performing marking the survivor objects.
● Any changes in the heap memory while performing garbage
Collection.
3. It will provide very good performance when compared with Parallel
Garbage Collector.
4. It is a more complicated Garbage Collector and it needs more
system Memory.
5. To activate this Garbage Collector we will use the following
command. D:\java9>java -XX:+UseConcMarkSeepGC Test

Garbage First [G1] Garbage Collector:


—--------------------------------
1. It was introduced in the JAVA7 version.
2. In this mechanism, it will divide heap memory into no of regions,
each region contains no of Grids, where each grid contains
Objects, Here Garbage Collection will be performed over all the
Grids that are Objects , if any useless object is identified then
it will be removed.
3. This mechanism is very simple and fast.
4. To activate this mechanism we have to use the following command.
D:\java9>java -XX:+UseG1GC Test

Garbage Collection Optimization Options:


—-----------------------------------
-Xms -----> Initial Heap Size.
-Xmx -----> Max Heap Size
-Xmn ----> Size of Young generation
-XX:PermSize ---> Initial Permanent Generation Size
-XX:MaxPermSize ---> Maximum Permanent Generation Size

EX:
D:\java9>java -Xmx12m -Xms3m -Xmn1m -XX:PermSize=20m -
XX:MaxPermSize=20m -XX:+UseSerialGC Test

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy