Java memory management

In languages like c, c++ memory management is done in explicitly by the developer. A small mistake in manually emptying the allocated memory may lead into memory leak. Then for applications that handle enormous amount of data, may run out of memory and lead to crash. But Java provides a mechanism for memory management. Garbage collection is the term used to describe automatic memory management in Java. Heap is the place where garbage collector works. Heap is part of memory where Java objects live. Hence garbage collector maintains as much free space in heap.

An object goes out of scope or it is eligible for deletion, when no living thread can access the object. Garbage collector is in control of Java Virtual Machine (JVM).If an object goes out of scope; we cannot ensure that immediately the garbage collector runs. JVM decides when to run Garbage collector as it senses that memory is running low.

When we write codes we can make objects eligible for garbage collection explicitly. One way is nulling references; means we remove references to objects by assigning that references to null. Then that object is eligible for garbage collection if no more references exist to that object in any live thread. The next way is to re assigning reference variables. Consider that we have two reference variables of Stringbuffer sb1 contains ‘hello’ and sb2 contains ‘world’. If we assigns sb1 = sb2 then the reference sb1 redirects to sb2 and the Stringbuffer ‘hello’ is eligible for garbage collection. Also we can make code eligible for garbage collection by isolation of a reference variable. For example if a class has instance variable which is a reference variable to another instance of the same class. Let such two instances refer to each other and all other references to these two object are removed. In this situation both the objects has valid reference, but no live thread can access either of the object. In this case also the garbage collector can find out this isolated set of objects and removes it.

We may make ‘requests’ not ‘demands’ explicitly to garbage collector. In order to do this we have to just include/use where we want “System.gc();”.It is just a request, the JVM handles the request. The protected void finalize() method something called just before the object is deleted. If an object is holding some non-Java resources like file handle, we can ensure by putting code into finalize().Even though there is automatic garbage collection, the system may run out of memory if we handle too many live objects. This indicates that garbage collection can only efficiently manage the available memory.