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.
1 |
Cleaner.<em>create</em>().register(this, () ->{<br> //Put your cleanup code here.<br>});<br> |
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:
1 |
package com.terrancedavis;<br><br>import java.lang.ref.Cleaner;<br>import java.util.concurrent.atomic.AtomicInteger;<br><br>public class CleanersExample<br>{<br> private static AtomicInteger <em>instanceCount </em>= new AtomicInteger(0);<br><br> public CleanersExample()<br> {<br><br> Cleaner.<em>create</em>().register(this, () ->{<br> System.<em>out</em>.println(<br> "Current instance count is "+<br> <em>instanceCount</em>.decrementAndGet()<br> );<br> });<br><br> System.<em>out</em>.println(<br> "Current instance count is "+<br> <em>instanceCount</em>.incrementAndGet()<br> );<br> }<br><br> public void sayHi()<br> {<br> System.<em>out</em>.println("Hi!");<br> }<br>}<br> |
Next the Main class to use the CleanersExample class:
1 |
import com.terrancedavis.CleanersExample;<br><br>public class Main<br>{<br><br> public static void main(String[] args)<br> {<br> new Main().usingSomeObjects();<br><br> System.<em>gc</em>();<br> try<br> {<br> Thread.<em>sleep</em>(5000);<br> }<br> catch (Exception e)<br> {<br> }<br><br> System.<em>out</em>.println("All done!");<br> }<br><br> private void usingSomeObjects()<br> {<br> CleanersExample ce1 = new CleanersExample();<br> CleanersExample ce2 = new CleanersExample();<br><br> ce1.sayHi();<br> ce2.sayHi();<br> }<br>} |
The output will look something like this.
Current instance count is 1
Current instance count is 2
Hi!
Hi!
Current instance count is 1
Current instance count is 0
All done!