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

Java Programming Java 8Object Oriented Programming

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 {}
raja
Published on 19-Sep-2018 10:19:45
Advertisements