[Read Effective Java] Chapter 2 Item 7 "Avoid Finalizers"

Avoid finalizers

Finalizers are unpredictable, usually dangerous, and generally not needed. There are some effective ways to use it, but basically it is better not to use it.

Glossary

Finalizer

The finalize () method. The finalize () method is defined in the java.lang.Object class, which is the inheritance source for all classes in the Java language. That is, every class has a finalize () method. A method called when the garbage collector runs.

Native peer

A native object that a regular object delegates through a native method. Since it is not a regular object, the garbage collector is unaware and cannot retrieve the native peer when the regular object is retrieved.

Finalizer chaining

If a class has a finalizer and a subclass overrides it, the finalizer for that subclass must manually call the finalizer for the superclass (Example 2).

Finalizer guardian

If a subclass implementor overrides a superclass finalizer and forgets to call the superclass finalizer, the superclass finalizer will never be called. Finalizer guardians are effective in protecting against such careless or malicious subclasses (Example 3).

Sample code

Example 1



//Try to guarantee execution of termination method-finally block
Foo foo = new Foo(...);
try {
    //Do what you have to do with foo
    ...
} finally {
    foo.terminate(); //Explicit termination method
}

Example 2


//Manual finalizer chain
@Override protected void finalize() throws Throwable {
    try {
        ... //Subclass finalizer processing
    } finally {
        super.finalize();
    }
}

Example 3


//Finalizer Guardian idiom
public class Foo {
    //The sole purpose of this object is to finalize the outer Foo object
    private final Object finalizerGuardian = new Object() {
        @Override protected void finalize() throws Throwable {
            ... //Finalize the outer Foo object
        }
    };
    ... //The rest is omitted
}

Two drawbacks of finalizer

First, there is no guarantee that the finalizer will be executed immediately.

• Time constraints should not be done in the finalizer, as the time it takes for the finalizer to run can be any length of time. · Never rely on finalizers to update critical persistent states

Second, there is a serious performance penalty for using the finalizer

Creating and releasing objects with finalizers is about 430 times slower than objects without them

What implementation should I implement instead of writing a finalizer?

-Provide an explicit termination method (Example 1) · Explicit termination methods are often used with try-finally syntax to guarantee termination

If the finalizer is enabled

First, when the owner of the object forgets to call the explicit termination method, it behaves as a "safety net".

Second, when collecting native peers

Continue

[Read Effective Java] Chapter 3 Item 8 "When overriding equals, follow the general contract" https://qiita.com/Natsukii/items/bcc5846dbfa69bfda9b0

Recommended Posts

[Read Effective Java] Chapter 2 Item 7 "Avoid Finalizers"
[Read Effective Java] Chapter 3 Item 10 "Always Override toString"
[Read Effective Java] Chapter 2 Item 5 "Avoid the creation of unnecessary objects"
[Read Effective Java] Chapter 2 Item 6 "Remove obsolete object references"
Effective Java Chapter 2
Effective Java Chapter 6 34-35
Effective Java Chapter 4 15-22
Effective Java Chapter 3
[Read Effective Java] Chapter 2 Item 4 "Force uninstantiation with a private constructor"
[Read Effective Java] Chapter 3 Item 9 "When overriding equals, always override hashCode"
[Read Effective Java] Chapter 2 Item 1 "Consider static factory methods instead of constructors"
[Read Effective Java] Chapter 3 Item 8 "When overriding equals, follow the general contract"
[Read Effective Java] Chapter 2 Item 3 "Force singleton characteristics with private constructor or enum type"
Effective Java 3rd Edition Chapter 5 Generics
Effective Java 3rd Edition Chapter 8 Methods
[Effective Java] Avoid creating unnecessary objects
[Read Effective Java] Chapter 2 Item 2 "Consider a builder when faced with a large number of constructor parameters"
Effective Java 3rd Edition Chapter 9 Program General
Effective Java 3rd Edition Chapter 6 enums and annotations
Effective Java 3rd Edition Chapter 7 Lambda and Streams
Effective Java 3rd Edition Chapter 2 Object Creation and Disappearance
Java Performance Chapter 1 Introduction
Read JSON in Java
Item 79: Avoid excessive synchronization
Read Java Property file
effective java 3rd summary
Read Java HashMap source
Builder pattern (Effective Java)
Java Performance Chapter 3 Java Performance Toolbox
Effective Java 3rd Edition Chapter 3 Methods Common to All Objects