What is the use of the Cleaner class in Java 9?


An Object that has been created during the program execution is automatically removed by Garbage Collector (GC). When an object not referenced by any thread and when JVM determines that this object can't be accessed, then it can be eligible for garbage collection.

The Object class has a finalize() method, which is automatically called by GC before it attempts to remove the object from the heap. In Java 9, the finalize() method has been deprecated and a new class java.lang.ref.Cleaner added to garbage collection management. An object of Cleaner class gets notified automatically when an object becomes eligible for garbage collection. An object that is being garbage collected needs to be registered with the cleaner object by using the register() method.

Example

import java.lang.ref.Cleaner;
public class CleanerTest {
   public static void main(String args[]) {
      System.out.println("TutorialsPoint");
      Cleaner cleaner = Cleaner.create();
      if(true) {
         CleanerTest myObject = new CleanerTest();
            cleaner.register(myObject, new State());    // register cleaner
      }
      for(int i = 1; i <= 10000; i++) {
         String[] largeObject = new String[1000];
         try {
            Thread.sleep(1);
         } catch(InterruptedException e) {
              e.printStackTrace();
         }
      }
   }
   private static class State implements Runnable {
      public void run() {
         System.out.print("Cleaning action");
      }
   }
}

Output

TutorialsPoint
Cleaning action

Updated on: 24-Feb-2020

638 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements