Replacing finalize() in Java

前端 未结 4 608
野趣味
野趣味 2020-12-05 07:47

Object.finalize() is deprecated in Java 9, and I think I understand the reasons why, but I\'m having trouble seeing how to replace it.

I have a utility

4条回答
  •  长情又很酷
    2020-12-05 08:20

    Java 9 introduces the Cleaner and Cleanable utility classes which take care of wiring up phantom references to a queue and a cleaning thread draining that queue.

    While this lets you separate out the witness that will perform a post-mortem cleanup after the owning object has died, all the caveats about GC-triggered resource management still apply, i.e. it is still preferable to rely on AutoClosable and try-with-resources blocks to manage the lifecycle of resources, not on the garbage collector.

提交回复
热议问题