Java : Cleaner.Cleanable with Examples

Cleaner.Cleanable (Java SE 21 & JDK 21) with Examples.
You will find code examples on most Cleaner.Cleanable methods.


Summary

Cleanable represents an object and a cleaning action registered in a Cleaner.

Class diagram

Please see also : Cleaner

class Foo {
}

final var foo = new Foo();
final var cleaner = Cleaner.create();

final var cleanable = cleaner.register(foo, () -> {
    System.out.println("Clean!");

    final var current = Thread.currentThread();
    System.out.printf("  (thread id = %d, daemon = %b)%n",
            current.threadId(), current.isDaemon());
});

System.out.println("-- start -- (thread id = " +
        Thread.currentThread().threadId() + ")");

cleanable.clean();

// Result
// ↓
//-- start -- (thread id = 1)
//Clean!
//  (thread id = 1, daemon = false)

Methods

void clean ()

Unregisters the cleanable and invokes the cleaning action.

class Foo {
}

final var foo = new Foo();
final var cleaner = Cleaner.create();

final var cleanable = cleaner.register(foo, () -> {
    System.out.println("Clean!");

    final var current = Thread.currentThread();
    System.out.printf("  (thread id = %d, daemon = %b)%n",
            current.threadId(), current.isDaemon());
});

System.out.println("-- start -- (thread id = " +
        Thread.currentThread().threadId() + ")");

cleanable.clean();

// Result
// ↓
//-- start -- (thread id = 1)
//Clean!
//  (thread id = 1, daemon = false)

Related posts

To top of page