Replacing Java’s finalize() Method

If you’ve reached Java 9 or above, you’ll notice at some point that the Java’s Object.finalize() method is deprecated. A quick look at the JavaDocs doesn’t give any easy solutions for a quick replacement. (Good luck with PhantomReferences, btw.)

So here’s a drop-in replacement that should have been documented, but I haven’t seen anyone mention this on Stack or anywhere else. Use a cleaner. If what you’re doing is simply destroying references, or something else similar, put the following code in your Java class constructor and copy the guts of finalize() into it. Then delete your old finalize() method.

Now you’re Java 9 compliant.

What you’re doing with this code change is creating a Runnable that is called when the Cleaner detects that your Object is in need of cleanup.

If you want to get really fancy, create only one cleaner and reference that one cleaner to register your objects during construction. That’s probably what you’ll do in any app that has a lot of objects that need cleaning up.

Here’s some code to make it a bit more clear how to use a Java Cleaner to replace a finalize() method.

First the CleanersExample class:

Next the Main class to use the CleanersExample class:

The output will look something like this.

Current instance count is 1
Current instance count is 2
Current instance count is 1
Current instance count is 0
All done!