File tree Expand file tree Collapse file tree
main/java/com/baeldung/finalize
test/java/com/baeldung/finalize Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments