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

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.

Leave a Comment