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()) {
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 , .