0% found this document useful (0 votes)
54 views

Garbage Collection

The document discusses garbage collection in Java. It explains that the garbage collector is responsible for freeing up memory from objects that are no longer referenced. It then describes various ways for an object to become eligible for garbage collection, such as nullifying references, reassigning references, or objects going out of scope. Finally, it discusses how to request that the garbage collector runs and the finalize() method.

Uploaded by

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

Garbage Collection

The document discusses garbage collection in Java. It explains that the garbage collector is responsible for freeing up memory from objects that are no longer referenced. It then describes various ways for an object to become eligible for garbage collection, such as nullifying references, reassigning references, or objects going out of scope. Finally, it discusses how to request that the garbage collector runs and the finalize() method.

Uploaded by

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

Garbage Collection

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 for 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.
 Java is robust, the chance of memory failing very less. (Memory
probably). One of reason is GC also, because the chance of failing java
program with memory problem very less because of garbage
collector. GC is part of the JVM.

The ways to make an object eligible for GC:

 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 longer required.
 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. Whenever JVM will run GC,
and then object will be destroy.
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:

Objects created inside a method are by default eligible for GC once method
completes.
Example 1:

Example2:
Example 3:

Example 4:
4. Island of Isolation:

Internal reference is there but no external reference, that’s why the group of
object is isolated from outside.

Note: if an object doesn't have any reference then it always eligible for GC.
Note: Even though object having reference still it is eligible for GC some times.

Example:
Island of isolation: (Island of Isolation all references are internal references)

The methods for requesting JVM to run GC:

 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
expect, 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();


// It will return (Same class Object) the Runtime object.
 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.

 At runtime, to run our program JVM required some memory.


 By using factory method we create object.

Note: Runtime class is a singleton class so not creates the object to use constructor.

Q) Which of the following are valid ways for requesting JVM to run GC?

System.gc(); (valid) // this method is static, that’s why we are calling by using class
name.
Runtime.gc(); (invalid) // this is instance method, so we should not use class
name.
(new Runtime).gc(); (invalid)
Runtime.getRuntime().gc(); (valid)

Note:
 gc() method present in System class is static, where as it is 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 size of an object and address of an object.

The internal implementation of the System class:


Class System {
public void static gc(){
Runtime.getRuntime().gc();
}
}

 Internally system class gc() method calling, runtime gc() method. So runtime
gc() method is performance wise good.

Finalization:

 Just before destroying any object GC always calls finalize() method


to perform cleanup activities.
 If the corresponding class contains finalize() method then it will
be executed otherwise Object class finalize() method will be
executed.
 GC can call on any object because it is available in Object class
that is super class for all java class.
Which is declared as follows? protected void finalize() throws Throwable

Case 1: Just before destroying any object GC calls finalize() method on the object
which is eligible for GC then the corresponding class finalize() method will be
executed.
For Example if String object is eligible for GC then String class finalize()method is
executed but not Test class finalize()method
 In the above program 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:

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

Case 2: 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.

class Test
{
public static void main(String args[]){
Test t=new Test();
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.

Case 3:

 Finalize () method can be call either by the programmer or by the GC.

 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 abnormally. If catch block is
there than normal termination.

 If catch block is there, both GC and program will execute if exception


raised.

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 terminated normally

Example:

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.

Q) 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).

 If catch block is there, JVM won’t ignore. Catch block will be executed.
 If catch block is not there then only JVM will ignore the exception.
Case 4: On any object GC calls finalize() method only once.

Note:
The behavior of the GC is vendor dependent and varied from JVM to JVM
hence we can't expert exact answer for the following.

1. What is the algorithm followed by GC.


2. Exactly at what time JVM runs GC.
3. In which order GC identifies the eligible objects.
4. In which order GC destroys the object etc.
5. Whether GC destroys all eligible objects or not.
 Whenever the program runs with low memory then the JVM runs GC,
but we can't expect exactly at what time.
 Most of the GC's followed mark & sweep algorithm, but it doesn't
mean every GC follows the same algorithm.

Case5:

#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.
Tools Example:
HPJ meter
HP ovo
IBM Tivoli These are monitoring tools.
(or memory management
J Probe tools)
Patrol and etc

To monitor Memory in java: Visual VM, Profiler4J, Java Interactive Profiler,


Eclipse Memory Analyzer, JRockit

Launch VisualVM

jvisualvm is available in bin fold of JDK.

You might also like