Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does Java's garbage collection free a memory allocation?

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?

like image 227
James Andino Avatar asked Jul 23 '10 03:07

James Andino


People also ask

What is the Java's mechanism process to free memory?

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.

Does garbage collector allocate 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.

How does garbage collector know which objects to free?

The garbage collector uses a traversal of the object graph to find the objects that are reachable.

Does GC release back memory to OS?

GC can reclaim and return the free memory to the host OS.


1 Answers

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.

like image 182
samitgaur Avatar answered Nov 03 '22 02:11

samitgaur