0% found this document useful (0 votes)
155 views5 pages

Garbage Collection: ND ND

1. Garbage collection is a process in Java where the Java Virtual Machine (JVM) automatically manages memory by identifying and removing objects that are no longer reachable. 2. An object is eligible for garbage collection if it is not referenced by any other objects. This can occur by nullifying the reference, reassigning the reference, or when an object is created within a method. 3. Programmers can request but not force garbage collection by calling methods like System.gc() or using the Runtime class, but the JVM determines when to actually perform collection.

Uploaded by

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

Garbage Collection: ND ND

1. Garbage collection is a process in Java where the Java Virtual Machine (JVM) automatically manages memory by identifying and removing objects that are no longer reachable. 2. An object is eligible for garbage collection if it is not referenced by any other objects. This can occur by nullifying the reference, reassigning the reference, or when an object is created within a method. 3. Programmers can request but not force garbage collection by calling methods like System.gc() or using the Runtime class, but the JVM determines when to actually perform collection.

Uploaded by

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

r Garbage Collection r Garbage Collection

nd
DURGASOFT, # 202,2ndFloor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
90 91  040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com

r Garbage Collection r Garbage Collection

Garbage Collection
1. Introduction:
2. The way to make an object eligible for GC
i. Nullifying the reference variable
ii. Reassign the reference variable
iii. Objects created inside a method
iv. Island of Isolation
3. The methods for requesting JVM to run GC
i. By System class
ii. By Runtime class
4. Finalization
o Case 1 : Just before destroying any object GC calls finalize() method on
the object
o Case 2 : We can call finalize() method explicitly
o Case 3 : finalize() method can be call either by the programmer or by the
GC
o Case 4 : On any object GC calls finalize() method only once
Memory leaks

Introduction:

 In old languages like C++ programmer is responsible for both creation and
destruction of objects. Usually programmer is taking very much care while
creating object and neglect destruction of useless objects .Due to his negligence at
certain point of time for creation of new object sufficient memory may not be
available and entire application may be crashed due to memory problems.
 But in java programmer is responsible only for creation of new object and his
not responsible for destruction of objects.
 Sun people provided one assistant which is always running in the background for
destruction at useless objects. Due to this assistant the chance of failing java
program is very rare because of memory problems.
 This assistant is nothing but garbage collector. Hence the main objective of GC is
to destroy useless objects.

The ways to make an object eligible for GC:

nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, DURGASOFT, # 202,2ndFloor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
92  040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
93
r Garbage Collection r Garbage Collection

 Even through programmer is not responsible for destruction of objects but it is


always a good programming practice to make an object eligible for GC if it is no Objects created inside a method are by default eligible for GC once method completes.
longer required. Example 1:
 An object is eligible for GC if and only if it does not have any references.

The following are various possible ways to make an object eligible for GC:

1.Nullifying 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.
Example:

2.Reassign the reference variable:

If an object is no longer required then reassign all its reference variables to some other
objects then old object is by default eligible for GC.

Example:

3. Objects created inside a method:

DURGASOFT, # 202,2ndFloor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, DURGASOFT, # 202,2ndFloor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
94 95

r Garbage Collection r Garbage Collection

Example 3:

Example 2:

DURGASOFT, # 202,2ndFloor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, DURGASOFT, # 202,2ndFloor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
96 97
r Garbage Collection r Garbage Collection

Example 4:

4.Island of Isolation:

DURGASOFT, # 202,2ndFloor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, DURGASOFT, # 202,2ndFloor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
98 99

r Garbage Collection r Garbage Collection

 Once we made an object eligible for GC it may not be destroyed immediately by


the GC. Whenever jvm runs GC then only object will be destroyed by the GC.
But when exactly JVM runs GC we can't expert it is vendor dependent.
 We can request jvm to run garbage collector programmatically, but whether jvm
accept our request or not there is no guaranty. But most of the times JVM will
accept our request.

The following are various ways for requesting jvm to run GC:

By System class:

System class contains a static method GC for this purpose.


Example:
System.gc();

By Runtime class:

 A java application can communicate with jvm by using Runtime object.


 Runtime class is a singleton class present in java.lang. Package.
 We can create Runtime object by using factory method getRuntime().

Example:

Runtime r=Runtime.getRuntime();

Once we got 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.

Example:
import java.util.Date;
class RuntimeDemo
{
public static void main(String args[]){
Runtime r=Runtime.getRuntime();
Note: if an object doesn't have any reference then it always eligible for GC. System.out.println("total memory of the heap :"+r.totalMemory());
Note: Even though object having reference still it is eligible for GC some times. System.out.println("free memory of the heap :"+r.freeMemory());
for(int i=0;i<10000;i++)
{
Example: Date d=new Date();
d=null;
island of isolation. (Island of Isolation all references are internal references ) }
System.out.println("free memory of the heap :"+r.freeMemory());
r.gc();
The methods for requesting JVM to run GC: System.out.println("free memory of the heap :"+r.freeMemory());
}
}
Output:
Total memory of the heap: 5177344

nd
DURGASOFT, # 202,2ndFloor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
100 101  040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
r Garbage Collection r Garbage Collection

Free memory of the heap: 4994920 Example:


Free memory of the heap: 4743408 class Test
Free memory of the heap: 5049776 {
Note : Runtime class is a singleton class so not create the object to use constructor. public static void main(String args[]){
String s=new String("bhaskar");
Test t=new Test();
Which of the following are valid ways for requesting jvm to run GC ? s=null;
System.gc(); (valid) System.gc();
Runtime.gc(); (invalid) System.out.println("End of main.");
(new Runtime).gc(); (invalid) }
Runtime.getRuntime().gc(); (valid) public void finalize(){
System.out.println("finalize() method is executed");
}
Note: gc() method present in System class is static, where as it is instance method in }
Runtime class. Output:
Note: Over Runtime class gc() method , System class gc() method is recommended to End of main.
use. In the above program String class finalize()method got executed. Which has empty
Note: in java it is not possible to find size of an object and address of an object. 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.

Finalization: Example:
class Test
{
 Just before destroying any object gc always calls finalize() method to perform public static void main(String args[]){
cleanup activities. String s=new String("bhaskar");
 If the corresponding class contains finalize() method then it will be executed Test t=new Test();
otherwise Object class finalize() method will be executed. t=null;
System.gc();
System.out.println("End of main.");
which is declared as follows.
protected void finalize() throws Throwable }
public void finalize(){
Case 1: System.out.println("finalize() method is executed");
}
}
Just before destroying any object GC calls finalize() method on the object which is Output:
eligible for GC then the corresponding class finalize() method will be executed. finalize() method is executed
End of main
For Example if String object is eligible for GC then String class finalize()method is
executed but not Test class finalize()method. Case 2:

DURGASOFT, # 202,2ndFloor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, DURGASOFT, # 202,2ndFloor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
102 103

r Garbage Collection r Garbage Collection

We can call finalize() method explicitly then it will be executed just like a normal
method call and object won't be destroyed. But before destroying any object GC always
calls finalize() method.

Example:
class Test
{
public static void main(String args[]){
Test t=new Test(); Diagram:
t.finalize();
t.finalize();
t=null;
System.gc();
System.out.println("End of main.");
}
public void finalize(){
System.out.println("finalize() method called");
}
}
Output:
finalize() method called.
finalize() method called.
finalize() method called.
End of main.

In the above program finalize() method got executed 3 times in that 2 times explicitly by
the programmer and one time by the gc.

Note: In Servlets we can call destroy() method explicitly from init() and service()
methods. Then it will be executed just like a normal method call and Servlet object
won't be destroyed.

DURGASOFT, # 202,2ndFloor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, DURGASOFT, # 202,2ndFloor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
104 105
r Garbage Collection r Garbage Collection

Case 3: System.gc();
Thread.sleep(5000);
System.out.println("end of main method");
finalize() method can be call either by the programmer or by the GC . }
public void finalize()
If the programmer calls explicitly finalize() method and while executing the finalize() {
method if an exception raised and uncaught then the program will be terminated System.out.println("finalize method called");
s=this;
abnormally. }
If GC calls finalize() method and while executing the finalize()method if an exception }
raised and uncaught then JVM simply ignores that exception and the program will be Output:
terminated normally. D:\Enum>java FinalizeDemo
4072869
finalize method called
Example: 4072869
class Test End of main method
{
public static void main(String args[]){
Test t=new Test();
//t.finalize();-------line(1) Note:
t=null; The behavior of the GC is vendor dependent and varied from JVM to JVM hence we
System.gc(); can't expert exact answer for the following.
System.out.println("End of main.");
}
public void finalize(){
System.out.println("finalize() method called");
System.out.println(10/0);
}

If we are not comment line1 then programmer calling finalize() method explicitly and
while executing the finalize()method ArithmeticException raised which is uncaught
hence the program terminated abnormally.
If we are comment line1 then GC calls finalize() method and JVM ignores
ArithmeticException and program will be terminated normally.

Which of the following is true?


While executing finalize() method JVM ignores every exception(invalid).
1. What is the algorithm followed by GC.
While executing finalize() method JVM ignores only uncaught exception(valid).
2. Exactly at what time JVM runs GC.
3. In which order GC identifies the eligible objects.
Case 4:
4. In which order GC destroys the object etc.
5. Whether GC destroys all eligible objects or not.
On any object GC calls finalize() method only once.
When ever the program runs with low memory then the JVM runs GC, but we can't
Example:
class FinalizeDemo except exactly at what time.
{ Most of the GC's followed mark & sweap algorithm , but it doesn't mean every GC
static FinalizeDemo s; follows the same algorithm.
public static void main(String args[])throws Exception{
FinalizeDemo f=new FinalizeDemo();
System.out.println(f.hashCode());
f=null;
System.gc();
Thread.sleep(5000);
System.out.println(s.hashCode());
s=null;

nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, DURGASOFT, # 202,2ndFloor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
106  040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
107

r Garbage Collection r Garbage Collection

Memory leaks:

 An object which is not using in our application and it is not eligible for GC such
type of objects are called "memory leaks".
 In the case of memory leaks GC also can't do anything the application will be
crashed due to memory problems.
 In our program if memory leaks present then certain point we will get
OutOfMemoryException. Hence if an object is no longer required then it's
highly recommended to make that object eligible for GC.
 By using monitoring tools we can identify memory leaks.

Example:

HPJ meter
HP ovo
IBM Tivoli These are monitoring tools.
J Probe (or memory management tools)
Patrol and etc

DURGASOFT, # 202,2ndFloor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, DURGASOFT, # 202,2ndFloor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
108 109

You might also like