How to replace the deprecated finalize() method from a Java 11 project with inter - dependencies among classes

userAsh :

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,

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");
    }
}
aashima :

So, the AutoCloseable interface with try-with-resources seems to be your best option by far. This alternative for finalize is, according to me, the simplest to implement - but this may of course vary depending on the complexity of each project.

class A must implement AutoCloseable class A implements AutoCloseable and all places where it's object is created should be enclosed in a try like try (A obj = new A())

Now go further and override the close method provided by AutoCloseable and make a call to destroy() from within.

class A implements AutoCloseable
{
    @Override
    public void close()
    {
        //log messages
        destroy();
    }
}

class X
{
    // suppose creating object of A within some method
    // enclose in try
    try ( A obj = new A ())
    {
        //use obj
    }
    // at the end of scope, the close() method of A will be called.
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=164535&siteId=1