devxlogo

Destroying Objects

Destroying Objects

Question:
In VB, you can release the object’s memory with the following:

set object = nothing

How do you accomplish the same thing in Java?

Answer:
The analogous way of doing this is to set an object to null:

object = null;

However, this does not immediately free the memory used by the classinstance. This only reduces the number of references to the memory byone. If this action causes the number of references to go down tozero, then the memory becomes eligible for garbage collection. Thegarbage collector does not immediately reclaim the memory, but mostJVMs will free the memory shortly afterward. You can ask the garbagecollector to run using System.gc(), which does not provide anyguarantee regarding when it will run, but often causes thegarbage collector to run immediately.

devx-admin

Share the Post: