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 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 anOutOfMemoryExceptionis 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.