Replacing finalize() in Java

前端 未结 4 581
野趣味
野趣味 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.
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-05 08:17

    Phantom references are general replacement for finalize(). Many classes from Java runtime are already using them.

    Using Phantom references is a bit laborious, you have to maintain own reference list and postmortem processing thread. On the other hand you are fully in control.

    Here is a simple example of Phantom reference setup.

    This article explains and compares implementation of Java finalize() and Phantom references.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题