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

JavaObject Oriented ProgrammingProgramming

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.


import java.lang.ref.Cleaner;
public class CleanerTest {
   public static void main(String args[]) {
      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 {
         } catch(InterruptedException e) {
   private static class State implements Runnable {
      public void run() {
         System.out.print("Cleaning action");


Cleaning action
Updated on 24-Feb-2020 05:31:36