Why would you ever implement finalize()?

前端 未结 21 2324
耶瑟儿~
耶瑟儿~ 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:22

    The accepted answer is good, I just wanted to add that there is now a way to have the functionality of finalize without actually using it at all.

    Look at the "Reference" classes. Weak reference, Phantom Reference & Soft Reference.

    You can use them to keep a reference to all your objects, but this reference ALONE will not stop GC. The neat thing about this is you can have it call a method when it will be deleted, and this method can be guaranteed to be called.

    As for finalize: I used finalize once to understand what objects were being freed. You can play some neat games with statics, reference counting and such--but it was only for analysis, but watch out for code like this (not just in finalize, but that's where you are most likely to see it):

    public void finalize() {
      ref1 = null;
      ref2 = null;
      othercrap = null;
    }
    

    It is a sign that somebody didn't know what they were doing. "Cleaning up" like this is virtually never needed. When the class is GC'd, this is done automatically.

    If you find code like that in a finalize it's guaranteed that the person who wrote it was confused.

    If it's elsewhere, it could be that the code is a valid patch to a bad model (a class stays around for a long time and for some reason things it referenced had to be manually freed before the object is GC'd). Generally it's because someone forgot to remove a listener or something and can't figure out why their object isn't being GC'd so they just delete things it refers to and shrug their shoulders and walk away.

    It should never be used to clean things up "Quicker".

提交回复
热议问题