Project Java Cleanup

Finalization done right.

This project is hosted on

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


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

Here's a snippet:

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

If the resource is auto-closeable you can use the even simpler method:

Where to get it?

The project is hosted on GitHub:

Download as JAR: cleanup.jar


Note: This might be out of date but you can generate this from the source using the ANT build file.


About the author: Home Page