Garbage Collection Java
Why Garbage Collection?
In Programming languages like C, C++ the programmer is responsible for both creation and deletion of objects. So if the programmer forget to delete the object then the memory allocated to those objects will no longer be available. This way the used memory will goes on increasing and there will be no memory left to allocate for other processes. This causes memory leaks. So at a certain point we may face memory out of bound exception and program gets terminated.
In general, we use some methods like free() or delete() to free up the memory in c and c++. But in Java, Garbage Collection is taken care automatically.
What is Garbage Collection in Java?
For every program to run there should be some memory allocated to it. After the task is completed the program should reclaim the memory it allocated. Garbage collection in Java is the process by which java performs automatic memory management.
In simple terms, Garbage Collection is defined as the process of reclaiming the memory no longer required by deleting the unused objects.
How Java Garbage Collection Works:
Java program first compiles to bytecode and then run on Java Virtual Machine(JVM) during which some memory is assigned to the program. During the course of time some objects will no longer be required and those to be deleted from the memory. This deletion is done by Garbage Collector.
Each JVM can have its own imlementation of garbage collection but they should follow JVM specification. The process involves below steps:
- First it will check the unreferenced objects and mark them for garbage collection.
- Then the marked objects are deleted
- There is optional sub-step where the compaction of memory(moving allocated memory together so that empty locations stay together) is done so that new objects can be allocated contiguous memory
some ways unreferencing an Object:
- By nullifying the reference
- By assigning reference to another
- objects created inside methods or blocks
We have discussed that dereferenced object is garbage collected. But How can an object be dereferenced
Example for by assigning reference to another:
Example of objects created inside methods or blocks:
The finalize() method, which is in Object class is called by Garbage Collector just before deletion of object. This method can be used to perform cleanup processing. This method is defined in Object class as:
protected void finalize throws Throwable{}
Example using finalize():
Output:
garbage collected
garbage collected
Advantages of Garbage Collection:
The biggest benefit of Java garbage collection is that it automatically handles the deletion of unused objects. If we work in any programming language that does not have garbage collection then we need to implement it manually.
It also makes Java memory-efficient because the garbage collector removes the unreferenced objects from heap memory. This frees the heap memory to accommodate new objects.
Comments
Post a Comment