initial commit for the BAEL-1479
This commit is contained in:
parent
3ecab4a0df
commit
30321eb801
|
@ -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();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -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();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue