Replacing finalize() in Java

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

    IMHO it's not the responsibility of your application to tell the logger to clean up its own mess. The logger itself can and should do it as (unlike IO streams or DB connections), it's supposed to live long.

    But you already provide logger.close()... OK, then I'd suggest the following:

    • Ensure that close is idempotent, i.e., closing the logger the second time is a no-op.
    • Use both Runtime#addShutdownHook and a PhantomReference, and let them both call logger.close(), so that it gets called both when the JVM terminates or your application gets GC'ed.

提交回复
热议问题