Item 8: Avoid finalizers and cleaners

笔记

  • Finalizers are unpredictable, often dangerous, and generally unnecessary. Cleaners are less dangerous than finalizers, but still unpredictable, slow, and generally unnecessary.
    两者的执行时间是不确定的。如果要用他们来释放资源,则资源得不到及时释放。最好是使用其他诸如try-with-resources或者try-finally等方式释放资源。

  • There is a severe performance penalty for using finalizers and cleaners.
    很慢。

  • Just have your class implement AutoCloseable, and require its clients to invoke the close method on each instance when it is no longer needed, typically using try-with-resources to ensure termination even in the face of exceptions (Item 9).
    这是普通开发人员用得着的方法:实现AutoCloseable接口,让使用者在try-with-resources中释放它。

  • They have perhaps two legitimate uses. One is to act as a safety net in case the owner of a resource
    neglects to call its close method. Some Java library classes, such as FileInputStream, FileOutputStream, ThreadPoolExecutor, and java.sql.Connection, have finalizers that serve as safety nets. second legitimate use of cleaners concerns objects with native peers.
    最后一道安全防护网。其实也没多大用处。普通开发人员根本用不着。
    这么说这些流不宜创建太多? 会影响性能?

  • The Cleaner spec says, “The behavior of cleaners during System.exit is implementation specific. No guarantees are made relating to whether cleaning actions are invoked or not.”
    不要依靠它来清理资源。

  • In summary, don’t use cleaners, or in releases prior to Java 9, finalizers, except as a safety net or to terminate noncritical native resources. Even then, beware the indeterminacy and performance consequences.

理解与思考

  • Cleaner和Finalizer只做防护网。不要对它有太多期望。
  • 资源自己管理,注意异常分支逻辑的处理。很多时候是异常分支导致了资源的泄露。
  • 有申请既要有释放。

实践

  1. cleaner的例子要在java9及以上版本才能跑。
  2. 要造成gc才能让cleaner执行资源清理操作。条用System.gc()都没用。

你可能感兴趣的:(Item 8: Avoid finalizers and cleaners)