0% found this document useful (0 votes)
8 views8 pages

Garbage Collection

Java garbage collection is an automatic memory management process that frees heap memory by destroying unreachable objects. It involves making objects eligible for garbage collection through nullifying or re-assigning reference variables and can be requested using System.gc() or Runtime.getRuntime().gc(). The heap is structured into generations, with the young generation hosting newly created objects and the old generation containing long-lived objects, and the process includes minor and major garbage collections to manage memory efficiently.

Uploaded by

Utkarsh Gupta
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)
8 views8 pages

Garbage Collection

Java garbage collection is an automatic memory management process that frees heap memory by destroying unreachable objects. It involves making objects eligible for garbage collection through nullifying or re-assigning reference variables and can be requested using System.gc() or Runtime.getRuntime().gc(). The heap is structured into generations, with the young generation hosting newly created objects and the old generation containing long-lived objects, and the process includes minor and major garbage collections to manage memory efficiently.

Uploaded by

Utkarsh Gupta
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/ 8

Garbage Collection in java

Java garbage collection is the process by which Java programs perform automatic memory
management.
Garbage collector is best example of Daemon thread as it is always running in
background.
Main objective of Garbage Collector is to free heap memory by
destroying unreachable objects.

Ways to make an object eligible for GC


1. Nullifying the reference variable
2. Re-assigning the reference variable
3. Object created inside method
4. Island of Isolation

Ways for requesting JVM to run Garbage Collector

 Once we made object eligible for garbage collection, it may not destroy
immediately by the garbage collector. Whenever JVM runs the Garbage
Collector program, then only the object will be destroyed. But when JVM
runs Garbage Collector, we can not expect.
 We can also request JVM to run Garbage Collector. There are two ways
to do it :
1. Using System.gc() method : System class contain static
method gc() for requesting JVM to run Garbage Collector.
2. Using Runtime.getRuntime().gc() method : Runtime
class allows the application to interface with the JVM in which the
application is running. Hence by using its gc() method, we can
request JVM to run Garbage Collector.

Note :
1. There is no guarantee that any one of above two methods will definitely
run Garbage Collector.
2. The call System.gc() is effectively equivalent to the
call : Runtime.getRuntime().gc()

Finalization
 Just before destroying an object, Garbage Collector
calls finalize() method on the object to perform cleanup activities.
Once finalize() method completes, Garbage Collector destroys that
object.
 finalize() method is present in Object class with following prototype.
protected void finalize() throws Throwable
Garbage Collection in java

Note :
1. The finalize() method called by Garbage Collector not JVM. Although
Garbage Collector is one of the module of JVM.
2. Object class finalize() method has empty implementation, thus it is
recommended to override finalize() method to dispose of system
resources or to perform other cleanup.
3. The finalize() method is never invoked more than once for any given
object.
4. If an uncaught exception is thrown by the finalize() method, the
exception is ignored and finalization of that object terminates.

Predict the output of following Java Programs:


 Program 1 :

public class Test


{
public static void main(String[] args) throws InterruptedException
{
String str = new String("GeeksForGeeks");

// making str eligible for gc


str = null;

// calling garbage collector


System.gc();

// waiting for gc to complete


Thread.sleep(1000);

System.out.println("end of main");
}

@Override
protected void finalize()
{
System.out.println("finalize method called");
}
}
Output:

end of main
Garbage Collection in java

Explanation : We know that finalize() method is called by Garbage


Collector on an object before destroying it. But here, the trick is that the
str is String class object, not the Test class. Therefore, finalize() method
of String class(if overridden in String class) is called on str. If a class
doesn’t override finalize method, then by default Object class finalize()
method is called.
 Program 2 :

public class Test


{
public static void main(String[] args) throws InterruptedException
{
Test t = new Test();

// making t eligible for garbage collection


t = null;

// calling garbage collector


System.gc();

// waiting for gc to complete


Thread.sleep(1000);

System.out.println("end main");
}

@Override
protected void finalize()
{
System.out.println("finalize method called");
System.out.println(10/0);
}

}
Output:
finalize method called
end main
Explanation :
When Garbage Collector calls finalize() method on an object,
it ignores all the exceptions raised in the method and program will
terminate normally.
 Program 3 :

public class Test


{
static Test t ;

static int count =0;


Garbage Collection in java

public static void main(String[] args) throws InterruptedException


{
Test t1 = new Test();

// making t1 eligible for garbage collection


t1 = null; // line 12

// calling garbage collector


System.gc(); // line 15

// waiting for gc to complete


Thread.sleep(1000);

// making t eligible for garbage collection,


t = null; // line 21

// calling garbage collector


System.gc(); // line 24

// waiting for gc to complete


Thread.sleep(1000);

System.out.println("finalize method called "+count+" times");

@Override
protected void finalize()
{
count++;

t = this; // line 38

}
Output:
finalize method called 1 times
Explanation :
After execution of line 12, t1 becomes eligible for garbage collection. So
when we call garbage collector at line 15, Garbage Collector will call
finalize() method on t1 before destroying it. But in finalize method, in
line 38, we are again referencing the same object by t, so after
execution of line 38,this object is no longer eligible for garbage
collection. Hence, Garbage Collector will not destroy the object.
Now again in line 21, we are making same object eligible for garbage
collection one more time. Here, we have to clear about one fact about
Garbage Collector i.e. it will call finalize() method on a particular object
exactly one time. Since on this object, finalize() method is already
Garbage Collection in java

called, so now Garbage Collector will destroy it without calling finalize()


method again.
 Program 4 :

public class Test


{
public static void main(String[] args)
{
// How many objects are eligible for
// garbage collection after this line?
m1(); // Line 5
}

static void m1()


{
Test t1 = new Test();
Test t2 = new Test();
}
}
Question :
How many objects are eligible for garbage collection after execution of
line 5 ?
Answer :
2
Explanation :
Since t1 and t2 are local objects of m1() method, so they become
eligible for garbage collection after complete execution of method
unless any of them is returned.
 Program 5 :

public class Test


{
public static void main(String [] args)
{
Test t1 = new Test();
Test t2 = m1(t1); // line 6
Test t3 = new Test();
t2 = t3; // line 8

static Test m1(Test temp)


{
temp = new Test();
return temp;
}
}
Question :
How many objects are eligible for garbage collection after execution of
Garbage Collection in java

line 8?
Answer :
1
Explanation :
By the time line 8 has executed, the only object without a reference is
the one generated i.e as a result of line 6. Remember that “Java is
strictly pass by value” so the reference variable t1 is not affected by the
m1() method. We can check it using finalize() method. The statement
“System.out.println(this.hashcode())” in finalize() method print the
object hashcode value on which finalize() method is called,and then just
compare the value with other objects hashcode values created in main
method.

Garbage Collection in java

https://java2blog.com/garbage-collection-java/

Describe in Detail How Generational Garbage


Collection Works
To properly understand how generational garbage collection works,
it is important to first remember how Java heap is structured to
facilitate generational garbage collection.
The heap is divided up into smaller spaces or generations. These
spaces are Young Generation, Old or Tenured Generation, and
Permanent Generation.
The young generation hosts most of the newly created
objects. An empirical study of most applications shows that
majority of objects are quickly short lived and therefore, soon
become eligible for collection. Therefore, new objects start their
journey here and are only “promoted” to the old generation space
after they have attained a certain “age”.
Garbage Collection in java

The term “age” in generational garbage collection refers to the


number of collection cycles the object has survived.
The young generation space is further divided into three spaces: an
Eden space and two survivor spaces such as Survivor 1 (s1) and
Survivor 2 (s2).
The old generation hosts objects that have lived in memory
longer than a certain “age”. The objects that survived garbage
collection from the young generation are promoted to this space. It
is generally larger than the young generation. As it is bigger in size,
the garbage collection is more expensive and occurs less frequently
than in the young generation.

The permanent generation or more commonly


called, PermGen, contains metadata required by the JVM to
describe the classes and methods used in the application. It also
contains the string pool for storing interned strings. It is populated
by the JVM at runtime based on classes in use by the application. In
addition, platform library classes and methods may be stored here.
First, any new objects are allocated to the Eden space. Both
survivor spaces start out empty. When the Eden space fills up, a
minor garbage collection is triggered. Referenced objects are moved
to the first survivor space. Unreferenced objects are deleted.
During the next minor GC, the same thing happens to the Eden
space. Unreferenced objects are deleted and referenced objects are
moved to a survivor space. However, in this case, they are moved to
the second survivor space (S2).
In addition, objects from the last minor GC in the first survivor space
(S1) have their age incremented and are moved to S2. Once all
surviving objects have been moved to S2, both S1 and Eden space
are cleared. At this point, S2 contains objects with different ages.
At the next minor GC, the same process is repeated. However this
time the survivor spaces switch. Referenced objects are moved to
S1 from both Eden and S2. Surviving objects are aged. Eden and S2
are cleared.
After every minor garbage collection cycle, the age of each object is
checked. Those that have reached a certain arbitrary age, for
Garbage Collection in java

example, 8, are promoted from the young generation to the old or


tenured generation. For all subsequent minor GC cycles, objects will
continue to be promoted to the old generation space.
This pretty much exhausts the process of garbage collection in the
young generation. Eventually, a major garbage collection will be
performed on the old generation which cleans up and compacts that
space. For each major GC, there are several minor GCs.

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