Skip to content

Instantly share code, notes, and snippets.

@misTrasteos
Last active December 27, 2021 13:27
Show Gist options
  • Save misTrasteos/5047d72529d7e941dfd72cca719e2be1 to your computer and use it in GitHub Desktop.
Save misTrasteos/5047d72529d7e941dfd72cca719e2be1 to your computer and use it in GitHub Desktop.
Java Cleaner API with AutoCloseable example
//JAVA_OPTIONS -Xms8m -Xmx8m -XX:+UseSerialGC
//JAVA_OPTIONS -XX:-DisableExplicitGC
/// https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/ref/Cleaner.html
import java.lang.AutoCloseable;
import java.lang.ref.Cleaner;
public class CleanerAPIAutoCloseableExample{
static class MyObjectCleaner implements Runnable{
@Override
public void run(){
System.out.println("Cleaning resources ...");
}
}
static class MyObject implements AutoCloseable{
static Cleaner cleaner = Cleaner.create();
Cleaner.Cleanable cleanable;
public MyObject(){
cleanable = cleaner.register(this, new MyObjectCleaner());
//cleanable = cleaner.register(this, () -> System.out.println("Cleaning resources from a lambda"));
}
@Override
public void close() {
this.cleanable.clean();
}
}
public static void main(String... args) throws Exception {
// ## using try-catch with resources
try( MyObject myObject = new MyObject()){}
// ## not using try-catch with resources
// cleaning action is also executed when the object become phanton reachable
MyObject myObject = new MyObject();
myObject = null;
System.gc();
Thread.sleep(10_000);
}
}
//JAVA_OPTIONS -Xms8m -Xmx8m -XX:+UseSerialGC
//JAVA_OPTIONS -XX:-DisableExplicitGC
import java.lang.ref.Cleaner;
public class CleanerAPIExample {
static class MyObject{
public int id;
public MyObject(int id){
this.id = id;
}
}
static class MyObjectCleaner implements Runnable {
int id;
static String text = "Cleaning resources for MyObject(%d)";
public MyObjectCleaner(int id) {
this.id = id;
}
@Override
public void run(){
System.out.println( String.format(text, id) );
}
}
public static void main(String... args) throws Exception {
Cleaner cleaner = Cleaner.create();
for(int i=0; i<=10; i++)
cleaner.register(new MyObject(i), new MyObjectCleaner(i) );
System.gc();
Thread.sleep(10_000);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment