If I have a method that takes a reader and I want to operate on the reader with a Scanner like so:
Scanner scanner = new Scanner(reader); while(scanner.hasNext()) { //blah blah blah }
Is it safe not to close scanner
? Documentation says that it "closes this scanner" and then talks about closing the underlying readable. Suppose I don't want to close the readable and instead want the caller to close reader
when ready. Is it safe not to close scanner
here?
Even though a scanner is not a stream, you need to close it to indicate that you're done with its underlying stream [1]. IDEs like Eclipse will often issue a warning that you have a "Resource leak: 'scanner' is never closed". Note: don't close a Scanner that's tied to System.in!
close() method closes this scanner. If this scanner has not yet been closed then if its underlying readable also implements the Closeable interface then the readable's close method will be invoked. If this scanner is already closed then invoking this method will have no effect.
Scanner class closes the scanner which has been opened. If the scanner is already closed then on calling this method, it will have no effect. Return Value: The function does not return any value.
Java Scanner close() Method The close() is a method of Java Scanner class which is used to closes this scanner.
It depends what you want to be safe against.
If you are just trying to ensure that the underlying stream is closed, then either approach is fine.
If you also want the Scanner
to be marked as closed (so that all subsequent operations on the object will fail immediately), then you should call Scanner.close()
.
This is a general principle; i.e. it also applies to various kinds of streams that do in-memory buffering, one way or another.
Since I already have the source code open :-) ...
The close()
method checks to see if the underlying Readable
also implements the Closeable
interface, and if it does it closes it. In your situation you are saying this is not a concern because it will be closed later.
But the close()
method also sets some internal flags indicating that the Scanner
(and underlying Readable
) are closed. Many of the public methods first check to see if the Scanner
has been closed. So the danger here would be that maybe your underlying Readable
has been closed, but further calls to the Scanner
don't immediately throw an IllegalStateException
, and instead fail in some other way as they proceed.
If you can ensure that nothing else has a handle to the Scanner
instance in question, and won't try to call any further methods on it, then you may be ok.
The close()
method also nulls out its reference to the Readable
, so if this doesn't happen the Scanner
wouldn't get garbage collected as soon as it would have had you called close()
.
I'd call Scanner.close()
if possible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With