How to prevent object of a class from garbage collection in Java?


If a object is no more referenced by a live reference then it becomes eligible for garbage collection. See the example below −

Example

public class Tester{
   public static void main(String[] args) {
      test();
   }

   public static void test(){
      A a = new A();
   }
}

class A {}

When test() method complete execution, the a object is no more referenced and is eligible for garbage collection. Java garbage collector will deallocate the object when it runs.

To prevent garbage collection, we can create a static reference to an object and then this object will not be garbage collected. See the example below −

Example

public class Tester{
   private static A a;
   public static void main(String[] args){
      test();
   }

   public static void test(){
      a = new A();
   }
}

class A {}

Updated on: 23-Jun-2020

191 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements