Project Java Cleanup

Finalization done right.

This project is hosted on https://github.com/claudemartin/java-cleanup/

Java 8 is needed to use any of the code!!

Is Java Cleanup the right thing for you?

Note that I was not aware of the existing Cleaner API. This was just a little side project. Later I found out that there already is sun.misc.Cleaner and we should get java.util.Cleaner with Java 9. So use that instead. Maybe this can still be used if you want to learn how to use PhantomReferences, but don't use it in production.

Do you know this situation: You have some java class and you need to cleanup after it was garbage collected?
You tried finalize but it didn't work or you have read that finalize should not be used.
Did you try PhantomReferences but found them to be hardly maintainable?
The interface Cleanup allows you to register cleanup actions for any object.
Implementing the interface Cleanup makes it even simpler.

There are still some pitfalls, but those are listed in the javadoc:
Javadoc for Cleanup

Example

A complete, working example can be found in the test folder: Example.java

Here's a snippet:

this.registerCleanup((value) -> {
  try {
    // 'value' instead of 'this.resource', so no reference to 'this' is leaked:
    value.close();
  } catch (Exception e) {
    logger.warning(e.toString());
  }
}, this.resource);

If the resource is auto-closeable you can use the even simpler method:
this.registerAutoClose(this.resource);

Where to get it?

The project is hosted on GitHub: https://github.com/claudemartin/java-cleanup

Download as JAR: cleanup.jar

Documentation

Javadoc: http://claude-martin.ch/java-cleanup/doc/
Note: This might be out of date but you can generate this from the source using the ANT build file.

History:

About the author: Home Page

Blog: http://humanoidreadable.wordpress.com/