Add - Is there a Destructor in Java (#12345)
This commit is contained in:
@@ -0,0 +1,17 @@
|
||||
package com.bealdung.java9.finalizers;
|
||||
|
||||
import java.lang.ref.Cleaner;
|
||||
|
||||
class CleaningDemo {
|
||||
|
||||
public static void main(String[] args) {
|
||||
final Cleaner cleaner = Cleaner.create();
|
||||
try (Order order = new Order(cleaner)) {
|
||||
for (int i = 0; i < 10; i++) {
|
||||
order.register(new Product(i), i);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
System.err.println("Error: " + e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.bealdung.java9.finalizers;
|
||||
|
||||
import java.lang.ref.Cleaner;
|
||||
|
||||
class Order implements AutoCloseable {
|
||||
|
||||
private final Cleaner cleaner;
|
||||
private Cleaner.Cleanable cleanable;
|
||||
|
||||
public Order(Cleaner cleaner) {
|
||||
this.cleaner = cleaner;
|
||||
}
|
||||
|
||||
public void register(Product product, int id) {
|
||||
this.cleanable = cleaner.register(product, new CleaningAction(id));
|
||||
}
|
||||
|
||||
public void close() {
|
||||
cleanable.clean();
|
||||
System.out.println("Cleanable closed");
|
||||
}
|
||||
|
||||
static class CleaningAction implements Runnable {
|
||||
|
||||
private final int id;
|
||||
|
||||
public CleaningAction(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
System.out.printf("Object with id %s is garbage collected. %n", id);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.bealdung.java9.finalizers;
|
||||
|
||||
class Product {
|
||||
private final int id;
|
||||
|
||||
public Product(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.bealdung.java9.finalizers;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.FileReader;
|
||||
|
||||
class Resource implements AutoCloseable {
|
||||
|
||||
final BufferedReader reader;
|
||||
|
||||
public Resource(String filename) throws FileNotFoundException {
|
||||
reader = new BufferedReader(new FileReader(filename));
|
||||
}
|
||||
|
||||
public long getLineNumber() {
|
||||
return reader.lines()
|
||||
.count();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws Exception {
|
||||
reader.close();
|
||||
System.out.println("BufferedReader resource closed");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user