How to prevent objects of a class from Garbage Collection in Java

The garbage collector in Java is automatic, i.e the user doesn’t have to manually free an occupied memory which was dynamically allocated. And how does a garbage collector decide which object is to be deleted? It’s simple: the object which loses it’s reference, is marked for deletion from the heap memory. For example, look at the following piece of code:





// Java code to demonstrate when an object would
// be deleted by the garbage collector
class A {
    void f()
        A x = new A(); /*object created locally
              It's scope remains valid till the
              termination of this function*/
    public static void main(String a[])
        /* function f() terminates, 
           and hence the object 'x' 
           too gets collected 
           by the garbage collector*/


The above code shows that the reference variable ‘x’ had a scope limited to the function ‘f()’. Therefore, after the termination of the mentioned function, the variable too has no recognition. Therefore, the object created loses it’s reference, and hence, is collected by the garbage collector.

The objects that are collected by the garbage collector, are collected so as to free the heap memory, where dynamic memory is allocated. The following diagram explains the different memory segments in a Java program, and their uses:

However, sometimes the question often arises: ‘Is there a way by which we can prevent an object from being collected by the garbage collector?’

There are several ways which can make objects undeletable in Java. They are discussed below:

By Increasing Heap Memory

Java allocates memory to it’s object in a partition called ‘heap’ (except for String and some other special objects which are allocated memory in pool). Since the heap memory is limited, some memory is always needed to be freed to accommodate space for new objects. However, we can, to some limit make objects undeletable by increasing the heap size. The following jvm command line parameters can get the job done: