Add - Is there a Destructor in Java (#12345)

This commit is contained in:
apeterlic 2022-06-13 22:22:57 +02:00 committed by GitHub
parent 2d9171f3a6
commit 151e2981b8
5 changed files with 121 additions and 0 deletions

View File

@ -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);
}
}
}

View File

@ -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);
}
}
}

View File

@ -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;
}
}

View File

@ -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");
}
}

View File

@ -0,0 +1,30 @@
package com.bealdung.java9.finalizers;
import org.junit.jupiter.api.Test;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import static org.junit.jupiter.api.Assertions.assertEquals;
class FinalizeUnitTest {
@Test
void givenFilename_whenGetLineNumber_thenReturnCorrectNumber() throws IOException {
final File tmpFile = File.createTempFile("test", ".tmp");
final BufferedWriter writer = new BufferedWriter(new FileWriter(tmpFile));
writer.write("Baeldung");
writer.close();
long lineNumber = 0;
try (Resource resource = new Resource(tmpFile.getAbsolutePath())) {
lineNumber = resource.getLineNumber();
} catch (Exception e) {
System.err.println("Error " + e);
}
assertEquals(1, lineNumber);
}
}