initial commit for the BAEL-1479

This commit is contained in:
Nam Thai Nguyen 2018-01-21 23:37:11 +07:00
parent 3ecab4a0df
commit 30321eb801
3 changed files with 83 additions and 0 deletions

View File

@ -0,0 +1,30 @@
package com.baeldung.finalize;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class CloseableResource implements AutoCloseable {
private BufferedReader reader;
public CloseableResource() {
InputStream input = this.getClass().getClassLoader().getResourceAsStream("file.txt");
reader = new BufferedReader(new InputStreamReader(input));
}
public String readFirstLine() throws IOException {
String firstLine = reader.readLine();
return firstLine;
}
@Override
public void close() {
try {
reader.close();
System.out.println("Closed BufferedReader in the close method");
} catch (IOException e) {
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.finalize;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class Finalizable {
private BufferedReader reader;
public Finalizable() {
InputStream input = this.getClass().getClassLoader().getResourceAsStream("file.txt");
reader = new BufferedReader(new InputStreamReader(input));
}
public String readFirstLine() throws IOException {
String firstLine = reader.readLine();
return firstLine;
}
@Override
public void finalize() {
try {
reader.close();
System.out.println("Closed BufferedReader in the finalizer");
} catch (IOException e) {
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.finalize;
import java.io.IOException;
import org.junit.Assert;
import org.junit.Test;
public class FinalizeUnitTest {
@Test
public void whenGC_thenFinalizerExecuted() throws IOException {
String firstLine = new Finalizable().readFirstLine();
Assert.assertEquals("baeldung.com", firstLine);
System.gc();
}
@Test
public void whenTryWResourcesExits_thenResourceClosed() throws IOException {
try (CloseableResource resource = new CloseableResource()) {
String firstLine = resource.readFirstLine();
Assert.assertEquals("baeldung.com", firstLine);
}
}
}