Replacing finalize() in Java

前端 未结 4 591
野趣味
野趣味 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:14

    You can add a Thread as shutdown hook to the Runtime:

    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        // cleanup code
    }));
    

    This is called when the VM terminates, so it should be a good replacement for finalize in your particular case

提交回复
热议问题