Why would you ever implement finalize()?

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

    finalize() is a hint to the JVM that it might be nice to execute your code at an unspecified time. This is good when you want code to mysteriously fail to run.

    Doing anything significant in finalizers (basically anything except logging) is also good in three situations:

    • you want to gamble that other finalized objects will still be in a state that the rest of your program considers valid.
    • you want to add lots of checking code to all the methods of all your classes that have a finalizer, to make sure they behave correctly after finalization.
    • you want to accidentally resurrect finalized objects, and spend a lot of time trying to figure out why they don't work, and/or why they don't get finalized when they are eventually released.

    If you think you need finalize(), sometimes what you really want is a phantom reference (which in the example given could hold a hard reference to a connection used by its referand, and close it after the phantom reference has been queued). This also has the property that it may mysteriously never run, but at least it can't call methods on or resurrect finalized objects. So it's just right for situations where you don't absolutely need to close that connection cleanly, but you'd quite like to, and the clients of your class can't or won't call close themselves (which is actually fair enough - what's the point of having a garbage collector at all if you design interfaces that require a specific action be taken prior to collection? That just puts us back in the days of malloc/free.)

    Other times you need the resource you think you're managing to be more robust. For example, why do you need to close that connection? It must ultimately be based on some kind of I/O provided by the system (socket, file, whatever), so why can't you rely on the system to close it for you when the lowest level of resource is gced? If the server at the other end absolutely requires you to close the connection cleanly rather than just dropping the socket, then what's going to happen when someone trips over the power cable of the machine your code is running on, or the intervening network goes out?

    Disclaimer: I've worked on a JVM implementation in the past. I hate finalizers.

提交回复
热议问题