Garbage Collector / Destructor in java
Java is a object oriented programming language. As we all know that: It supports Objects, Methods, Variables, etc. When we create a new Object, It allocates space required for the class in HEAP memory of JAVA. Which can not be removed by any function call. That space is totally under control of JVM – Java Virtual Machine. So, We can conclude that there is no concept like destructor in java. But for the memory management Java supports Garbage Collector mechanism.
What is Garbage Collector?
- It is a utility of Java Virtual Machine which is used to reclaim the space/memory allocated previously.
- Compared to C++, in Java the developer need not to worry about freeing the memory.
- Garbage Collection is done by a Thread named as: Garbage Collector
- Developer can not invoke Garbage collector. It is controlled by JVM. When JVM thinks that there is a need of removing memory, It starts the Garbage Collector Thread.
- But we can of course send a request to JVM that: “Please invoke Garbage Collector!”. But it is just a request to JVM. It’s not a call. Garbage Collector may or may not be invoked. Commands to send such request are: 1) System.gc() 2) Runtime.gc().
- One most important part of Garbage Collector is: When garbage collector is invoked by JVM, finalize() method of our program will be invoked by JVM. So that developer can write/execute some code at that time.
Which objects will be removed by Garbage Collector?
- Objects which are no where used further.
- In case object has multiple referenced, All the references of that object are not used further.
- Objects which are created inside a block and execution of that block is over
- When parent object is not gonna used further, All the child objects are also unused.
Above listed kind of objects will be removed by Garbage Collector.
void finalize()
As discussed above, a method named finalize() will be invoked when Garbage Collector is gonna remove the memory(object) of that class. So, that developer can write his end moment code. You can refer the below code to learn: How to write finalize() method.
import java.io.*; class OpenAFile { FileInputStream aFile = null; String filename = ""; OpenAFile(String filename) { this.filename = filename; try { aFile = new FileInputStream(filename); }catch (java.io.FileNotFoundException e) { System.err.println("Could not open file " + filename); } } public void finalize () { try { if (aFile != null) { aFile.close(); aFile = null; } }catch (Exception e) { System.err.println("Could not close" + filename); } } }
Let me know in case you have any question.
Community Answers
Trackbacks/Pingbacks