In Java programming language, garbage collection is performed by JVM. JVM determines the objects which are no longer used in a program to free up memory space.
When objects are created using new
, there is no delete operation to reclaim memory space. Though in some other object oriented languages like C++, there is a concept of destructor. Even if you set null to an object reference, the memory space is not freed. Thus the process by which JVM finds and reclaims these memory space is known as garbage collection.
JVM performs garbage collection without your intervension and you have no direct control over it.
But, you can implement a finalize
method, which will be executed before an object's memory is reclaimed, though this one is rarely used. You should write finalize
method with great care as it may craete a scenario where other objects refers to the garbage.
Garbage collector collects only memory, not non-memory resources. If you open a file in your program, you have to close it.
Here, the following program demonstrates garbage collection.
As we have discussed that there is no way to free unused objects, but you can call garbage collector explicitly as shown below.
First we are printing available memory in JVM and then garbage collection is performed using gc method of RunTime class, and finally the available memory is printed after garbage collection.
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.