I have created an object in Java, Named FOO. FOO contains a large amount of data.. I don't know say for a ten mega byte text file that I have pulled into ram for manipulation.(This is just an example)
This is clearly a huge amount of space and I want to deallocate it from memory. I set FOO to NULL.
Will this free up that space in memory automatically? or Will the memory taken by the loaded text file be around until automatic garbage collection?
When Java programs run on the JVM, objects are created on the heap, which is a portion of memory dedicated to the program. Eventually, some objects will no longer be needed. The garbage collector finds these unused objects and deletes them to free up memory.
The garbage collector allocates and frees virtual memory for you on the managed heap. If you're writing native code, you use Windows functions to work with the virtual address space. These functions allocate and free virtual memory for you on native heaps.
The garbage collector uses a traversal of the object graph to find the objects that are reachable.
GC can reclaim and return the free memory to the host OS.
When you set the reference of any object to null
, it becomes available for garbage collection. It still occupies the memory until the garbage collector actually runs. There are no guarantees regarding when GC will run except that it will definitely run and reclaim memory from unreachable objects before an OutOfMemoryException
is thrown.
You can call System.gc() to request garbage collection, however, that's what it is - a request. It is upto GC's discretion to run.
Using a WeakReference can help in some cases. See this article by Brian Goetz.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With