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()
I've been doing Java professionally since 1998, and I've never implemented finalize()
. Not once.
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); } }
finalize()
can be useful to catch resource leaks. If the resource should be closed but is not write the fact that it wasn't closed to a log file and close it. That way you remove the resource leak and give yourself a way to know that it has happened so you can fix it.
I have been programming in Java since 1.0 alpha 3 (1995) and I have yet to override finalize for anything...