So today, we're going to destroy objects manually. Actually we don't need to perform this manually since Java itself do this for us.
As you know, java stores all the created objects in its heap memory. So when we create more and more objects and let them in the help, eventually heap will come to its maximum capacity. That is why we need to identify what are the objects program is currently using, and what are the objects it doesn't use anymore and then we need to remove that unused objects to get space inside the heap memory. This process is called Garbage Collection.
Now let's see what are the possibilities that an object is eligible for garbage collection. There are 2 identified scenarios.
The object no longer has any references pointing to it.
All references to the object have gone out of scope.
So how an object will get no references pointing to it ?
If you can remember we discussed this in our previous post. You have to have a clear idea about that in order to understand this. Anyways, in brief this is the case,
Have a look at the above picture and let's assume we have an object like that.
then, this object can get no references by,
- Nulling the reference.
- Assigning the reference to another object.
- Anonymous object.
Alright, now you know what's happening behind garbage collection. Now let's see how we can perform garbage collection.
In Java, it provides a method called System.gc() to run garbage collection. In the actual scenario, when we execute System.gc() it doesn't do the garbage collection, instead it suggest java that this maybe a good time to run garbage collection. So then garbage collection might or might not happen.
There is one more thing regarding garbage collection, its finalize() method. There's nothing much about this method, this method gets called if the garbage collector tries to collect the object. And this method only get called once. Which means, if garbage collector runs and collect garbage, that's okay. If garbage collector runs and fails to collect garbage and if it runs again, finalize() won't run. Basically, It might get called, but it will never run twice.
That's pretty much about garbage collections. Let's meet in another :)