Why would you ever implement finalize()?

前端 未结 21 2375
耶瑟儿~
耶瑟儿~ 2020-11-22 16:50

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()

相关标签:
21条回答
  • 2020-11-22 17:45

    I've been doing Java professionally since 1998, and I've never implemented finalize(). Not once.

    0 讨论(0)
  • 2020-11-22 17:45

    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);
            }
        }
    
    0 讨论(0)
  • 2020-11-22 17:47

    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...

    0 讨论(0)
提交回复
热议问题