0 votes
1 view
in Java by (5.4k points)

I've been reading through a lot of the rookie Java questions on finalize() and find it kind of bewildering that no one has really made it plain that finalize() is an unreliable way to clean up resources. I saw someone comment that they use it to clean up Connections, which is really scary since the only way to come as close to a guarantee that a Connection is closed is to implement try (catch) finally.

I was not schooled in CS, but I have been programming in Java professionally for close to a decade now and I have never seen anyone implement finalize() in a production system ever. This still doesn't mean that it doesn't have its uses, or that people I've worked with have been doing it right.

So my question is, what use cases are there for implementing finalize()that cannot be handled more reliably via another process or syntax within the language?

Please provide specific scenarios or your experience, simply repeating a Java text book, or finalize's intended use is not enough, as is not the intent of this question.

1 Answer

0 votes
by (66.4k points)

It can be handy to remove things that have been added to a global/static place (out of need), and need to be removed when the object is removed. For instance:

 private void addGlobalClickListener() {

        weakAwtEventListener = new WeakAWTEventListener(this);

  Toolkit.getDefaultToolkit().addAWTEventListener(weakAwtEventListener, AWTEvent.MOUSE_EVENT_MASK);

    }

    @Override

    protected void finalize() throws Throwable {

        super.finalize();

        if(weakAwtEventListener != null) {

         Toolkit.getDefaultToolkit().removeAWTEventListener(weakAwtEventListener);

        }

    }

If you want to learn Java from the top experts, you can register in this Java Course program by Intellipaat.

Related questions

0 votes
1 answer
0 votes
1 answer
asked Jul 13, 2019 in Java by Shubham (3.9k points)
0 votes
1 answer
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...