NOTE

  1. Never do anything time-critical in a finalizer.
  2. Never depend on a finalizer to update critical persistent state.
  3. There is a severe performance penalty for using.
  4. "Finalizer chaining" is not performed automatically. The subclass finalizer must invoke the superclass finalizer manually.
    1. Manual finalizer chaining

    @Override

    protected void finalize() throws Throwable {

    try {

    ... // Finalize subclass state

    } finally {

    super.finalize();

    }

    }

    b. Finalizer Guardian idiom

    // Finalizer Guardian idiom. This will prevent the subclass forgets to invoke super class's finalize method.

    public class Foo {

    // Sole purpose of this object is to finalize outer Foo object

    private final Object finalizerGuardian = new Object() {

    @Override protected void finalize() throws Throwable {

    ... // Finalize outer Foo object

    }

    };

    ... // Remainder omitted

    }

What to do

  1. Provide an explicit termination method

the explicit termination method must record in a private field that the object is no longer valid, and other methods must check this field and throw an IllegalStateException if they are called after the object has been terminated.

  1. Explicit termination methods are typically used in combination with the try-finally construct to ensure termination.

    // try-finally block guarantees execution of termination method

    Foo foo = new Foo(...);

    try {

    // Do what must be done with foo

    ...

    } finally {

    foo.terminate(); // Explicit termination method

    }

Usage of finallizer

  1. Safety net: ensure the resources being released even if the explicitly termination method is not executed correctly.

    Note: the finalizer should log a warning if it finds that the resource has not been terminated

  2. Concerns objects with native peers. A native peer is a native object to which a normal object delegates via native methods. Because a native peer is not a normal object, the garbage collector doesn't know about it and can't reclaim it when its Java peer is reclaimed. A finalizer is an appropriate vehicle for performing this task, assuming the native peer holds no critical resources.

Summary

In summary, don't use finalizers except as a safety net or to terminate noncritical native resources. In those rare instances where you do use a finalizer, remember to invoke super.finalize. If you use a finalizer as a safety net, remember to log the invalid usage from the finalizer. Lastly, if you need toassociate a finalizer with a public, nonfinal class, consider using a finalizer guardian, so finalization can take place even if a subclass finalizer fails to invoke super.finalize.

Effective Java 07 Avoid finallizers More articles about

  1. Effective Java 67 Avoid excessive synchronization

    Principle To avoid liveness and safety failures, never cede control to the client within a synchroni ...

  2. Effective Java 50 Avoid strings where other types are more appropriate

    Principle Strings are poor substitutes for other value types. Such as int, float or BigInteger. Stri ...

  3. Effective Java 73 Avoid thread groups

    Thread groups were originally envisioned as a mechanism for isolating applets for security purposes. ...

  4. Effective Java 05 Avoid creating unnecessary objects

    String s = new String("stringette"); // Don't do this. This will create an object each tim ...

  5. Effective Java 48 Avoid float and double if exact answers are required

    Reason The float and double types are particularly ill-suited for monetary calculations because it i ...

  6. Effective Java 59 Avoid unnecessary use of checked exceptions

    The burden is justified if the exceptional condition cannot be prevented by proper use of the API an ...

  7. Effective Java Index

    Hi guys, I am happy to tell you that I am moving to the open source world. And Java is the 1st langu ...

  8. Effective Java Create and destroy objects

    <Effective Java> Reading notes , Refine the book in a way that suits your understanding .<Effective Java> It's a very practical book , The reading method should be quick to understand , summary , Then apply . Instead of , One ...

  9. Effective Java The third edition ——22. Interfaces are only used to define types

    Tips <Effective Java, Third Edition> An English version of the book has been published , The second edition of this book must have been read by many people , It's called Java One of the four masterpieces , But the second edition 2009 Published in , By now it has been ...

Random recommendation

  1. .NET4.5 WFP of use WebBrowser obtain / Operate the web html Code

    introduction I want to update my previous web novel crawler program , I used to use winform A program written in the form of , So this update is going to put UI Switch to WPF( Because I heard WPF It's pretty. ), By the way, it also introduces WPF Learning from . So as a web crawler ...

  2. Markdown(MD) writing

    Simple writing It is being used gradually Makedown To write blogs or other documents , This article records Markdown Knowledge about Markdown grammar title # Content ( First level title ) ## Content ( Secondary title ) ### Content ( 3、 ... and ...

  3. Linux Next Console / Console Copy and paste shortcuts

    Linux Next copy and paste shortcut 1. Under the terminal : Copy command :Ctrl + Shift + C  Composite key . Paste command :Ctrl + Shift + V  Composite key . 2. Under the console : Copy command :Ctrl + ...

  4. 【BZOJ 3524】【Poi2014】Couriers Persistent line tree

    Why is this chairman tree called a persistent line segment tree , I don't know , To be specific, ask Da Shen . I'm infinite T, then DaD3zZ To the point of my N*50 Memory explosion causes infinite compilation timeout O)ZO)ZO)Z It's amazing . Learn from the picture : Teleportation gate :http ...

  5. Mysql-- Learning notes (==》 Simple query 3 )

    -- View query data display SELECT * FROM student; -- A query that displays part of the information SELECT sname full name ,sscore achievement ,saddress Home address FROM student; ...

  6. JavaScript New tools for heap memory analysis OneHeap

    OneHeap Focus on running JavaScript Display of memory information , It's restored in a visual way HeapGraph, Help to understand v8 memory management . background JavaScript Most of the data in the running process is stored in ...

  7. Oracle Patches and opatch Tool is introduced

    One . CPU(Critical Patch Update) One CPU Contains fixes for multiple security vulnerabilities , And also includes the corresponding necessary non security vulnerability patches .CPU It's cumulative , Just install the latest CPU that will do , Including the previous ...

  8. Easy to understand python Closures and decorators in ( On )

    After object-oriented programming, functional programming is becoming more and more popular , stay python Functional programming is also supported in , We usually use map, reduce, filter And so on are examples of functional programming . In functional programming , Function also exists as a variable , Corresponding ...

  9. Nginx And ( One )Nginx What is it?

    Nginx("engine x") It's a lightweight model Web The server / Reverse proxy server and email (IMAP/POP3) proxy server . By Russian programmers Igor Sysoev The development of , For the Russian big ...

  10. Unity plug-in unit - MeshEditor( 6、 ... and ) Morphing animation state machine

    Morphing animation state machine --MeshAnimator, Is aimed at MeshAnimation State manager of , There are a lot of similar Unity animator The function of , but MeshAnimator It will be easier to operate , More intuitive , Home travel (zh ...