Is the completion of an object the same as its nullification?

So, I went through "Effective Java 2nd Ed."

In paragraph 7, he says that he does not use finalizers, because they can cause a lot of problems.

But instead of using finalizers, we can "provide an explicit termination method", and an example of this is the close operator. and I didn’t understand what the "statements of completion" are and what are the differences between them and the finalizers?

I came to the conclusion that completing an object is similar to nulling it, so resources are freed. but I think I don’t understand the difference, which is good. so I appreciate any help.

Thank!

+4
source share
2 answers

" ", close.

close(), , .

, InputStream OutputStream, Java ( . , FileInputStream, finalize()), , , , API, : void close(), .

java.sql.Statement : close() JDBC, .

, , .

null , . , - , -

, .
, ?

+8

finalize() , . , , , . .

class Foo {
    @Override
    public void finalize() {
        System.out.println("Finalize Foo");
    }
}

class Bar implements Closeable {
    @Override
    public void close() {
        System.out.println("Close Bar");
    }
}

class Baz implements AutoCloseable {
    @Override
    public void close() {
        System.out.println("Close Baz");
    }
}

finalize(), Object. Foo Bar , ARM ( ).

Foo foo = new Foo();
new Foo();
try (Bar bar = new Bar(); Baz baz = new Baz()) { // this is ARM 
    System.out.println("termination example");
}
Bar bar = null;
try {
    bar = new Bar();
    // ...
} finally {
    if (bar != null) {
        bar.close();
    }
}

:

termination example
Close Baz
Close Bar
Close Bar

finalize() Foo , Foo . JVM , . - , , . Foo - , JVM .

ARM , ( java.io.Closeable java.lang.AutoCloseable, , Closeable extends AutoCloseable, ARM). ARM , , , . ARM, .

- :

. - . Java , ARM . ( Venkat Subramaniam) - Loan Pattern. :

class Loan {
    private Loan() {
    }

    public Loan doSomething(int m) {
        System.out.println("Did something " + m);
        if (new Random().nextBoolean()) {
            throw new RuntimeException("Didn't see that commming");
        }
        return this;
    }

    public Loan doOtherThing(int n) {
        System.out.println("Did other thing " + n);
        return this;
    }

    private void close() {
        System.out.println("Closed");
    }

    public static void loan(Consumer<Loan> toPerform) {
        Loan loan = new Loan();
        try {
            toPerform.accept(loan);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            loan.close();
        }
    }
}

:

class Main {
    public static void main(String[] args) {
        Loan.loan(loan -> loan.doOtherThing(2)
                .doSomething(3)
                .doOtherThing(3));
    }
}

, . , , . close , .

+1

Source: https://habr.com/ru/post/1678557/


All Articles