My goal is to understand on how to properly override close()
method from java.io.Closeable
.
I actually don't understand why some class like java.util.Scanner
close()
method only change the field closed
to true and then on next()
method it always do the ensureOpen()
method before executing other method, essentially it makes me to think that close()
method is just for the aesthetic aspect instead of to prevent memory leak
.
I tried to create a test, based on assumption that close()
method
Closeable Closes this stream and releases any system resources associated with it. If the stream is already closed then invoking this method has no effect.
My expected result: printer.println("should not print");
should fail.
My actual result: printer.println("should not print");
print the result.
Application.java
import java.io.IOException;
public class Application {
public static void main(String[] args) {
final Printer printer = new Printer();
try (printer) {
printer.println("hello");
} catch (IOException e) {
e.printStackTrace();
}
printer.println("should not print");
}
}
Printer.java
public class Printer implements Closeable {
public void println(String x) {
System.out.println(x);
}
@Override
public void close() throws IOException {
System.out.println(Printer.class + " close");
}
}
EDIT: Following the discussion with @Turing85, I am following the java.util.Scanner
pattern to use flag-option
public class Printer implements Closeable {
private boolean closed = false;
private void ensureOpen() {
if (this.closed)
throw new IllegalStateException("Printer closed");
}
public void println(String x) {
ensureOpen();
System.out.println(x);
}
@Override
public void close() throws IOException {
this.closed = true;
System.out.println("Printer closed");
}
}