Clean up code in finalize() or finally()?

前端 未结 9 1036
不知归路
不知归路 2020-12-19 04:16

I had the general view that clean up of resources is done in the finally block,
recently I found this particular code snippet in a class and it was overridi

9条回答
  •  [愿得一人]
    2020-12-19 04:41

    Phantom References will do what you want.

    Just don't use finalize. There are a few edge cases where it may be helpful (printing debug info when a class is GC'd has come in handy), but in general don't. There is nothing in the JVM contract that even says it ever has to be called.

    There is a very under-publicized type of object called "References". One is made explicitly for things that you think you would use finalize for.

    "Phantom reference objects, which are enqueued after the collector determines that their referents may otherwise be reclaimed."

    It just occurred to me that there MUST be a description of this on the web--so I'll replace all the "how-to" stuff I just wrote with this reference.

提交回复
热议问题