Skip to content

Commit 30321eb

Browse files
Nam Thai NguyenNam Thai Nguyen
authored andcommitted
initial commit for the BAEL-1479
1 parent 3ecab4a commit 30321eb

3 files changed

Lines changed: 83 additions & 0 deletions

File tree

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package com.baeldung.finalize;
2+
3+
import java.io.BufferedReader;
4+
import java.io.IOException;
5+
import java.io.InputStream;
6+
import java.io.InputStreamReader;
7+
8+
public class CloseableResource implements AutoCloseable {
9+
private BufferedReader reader;
10+
11+
public CloseableResource() {
12+
InputStream input = this.getClass().getClassLoader().getResourceAsStream("file.txt");
13+
reader = new BufferedReader(new InputStreamReader(input));
14+
}
15+
16+
public String readFirstLine() throws IOException {
17+
String firstLine = reader.readLine();
18+
return firstLine;
19+
}
20+
21+
@Override
22+
public void close() {
23+
try {
24+
reader.close();
25+
System.out.println("Closed BufferedReader in the close method");
26+
} catch (IOException e) {
27+
e.printStackTrace();
28+
}
29+
}
30+
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package com.baeldung.finalize;
2+
3+
import java.io.BufferedReader;
4+
import java.io.IOException;
5+
import java.io.InputStream;
6+
import java.io.InputStreamReader;
7+
8+
public class Finalizable {
9+
private BufferedReader reader;
10+
11+
public Finalizable() {
12+
InputStream input = this.getClass().getClassLoader().getResourceAsStream("file.txt");
13+
reader = new BufferedReader(new InputStreamReader(input));
14+
}
15+
16+
public String readFirstLine() throws IOException {
17+
String firstLine = reader.readLine();
18+
return firstLine;
19+
}
20+
21+
@Override
22+
public void finalize() {
23+
try {
24+
reader.close();
25+
System.out.println("Closed BufferedReader in the finalizer");
26+
} catch (IOException e) {
27+
e.printStackTrace();
28+
}
29+
}
30+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package com.baeldung.finalize;
2+
3+
import java.io.IOException;
4+
5+
import org.junit.Assert;
6+
import org.junit.Test;
7+
8+
public class FinalizeUnitTest {
9+
@Test
10+
public void whenGC_thenFinalizerExecuted() throws IOException {
11+
String firstLine = new Finalizable().readFirstLine();
12+
Assert.assertEquals("baeldung.com", firstLine);
13+
System.gc();
14+
}
15+
16+
@Test
17+
public void whenTryWResourcesExits_thenResourceClosed() throws IOException {
18+
try (CloseableResource resource = new CloseableResource()) {
19+
String firstLine = resource.readFirstLine();
20+
Assert.assertEquals("baeldung.com", firstLine);
21+
}
22+
}
23+
}

0 commit comments

Comments
 (0)