I have a Java 11 project involving multiple classes. In the present scenario, 2 of my classes - A and B - implement the java finalize() method, which is now deprecated for good. I understand the method may not be removed in the near future but I think it best to find a replacement for finalize right away.
finalize() in class A is mainly focused destroying an object of long type which is a protected member variable and on printing certain messages to log. finalize() in class B simply prints certain messages to log.
Instances of class A are created from several other classes and class B extends another class ClassLoader. (Code snippets included below.)
I went through quite a few suggestions such as,
- Autocloseable with try-with-resources
- Cleanable interface ( https://humanoid-readable.claude-martin.ch/2014/07/30/finalize/ )
- try-catch-finally
These are explained not so well in the first place and even when they are, the examples are specific to single class projects with the main method present in the same class. I'm unable to move forward with the minimal solution that I found online.
Post my research, Autocloseable with try-with-resources seems to be my best option. I understand that my classes A and B should implement Autocloseable while the callees (A bit unsure here) should use try-with-resources.
I will be grateful for any help towards simplifying this problem even if it is to fill the gaps that may be present in my understanding of the scenario.
A.java
class A
{
protected long a_var;
protected A(String stmt, boolean isd)
{
// a_var is initialized here
}
public void finalize()
{
if(a_var != 0)
{
log("CALL destroy !");
destroy(a_var);
log("DONE destroy !");
}
}
}
B.java
public class B extends extends ClassLoader
{
protected void finalize ()
{
log("No action");
}
}