Is it safe not to close a Java Scanner, provided I close the underlying readable?

天大地大妈咪最大 提交于 2019-11-27 19:39:51

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.

David

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.

Chris

I needed to close the Scanner as well, and keep the underlying stream open for further work. What I did is create a class that extends BufferedInputStream and overrides the close() method with an empty body. This class I fed into the constructor of the Scanner. This way, you can call scanner.close() without closing the stream. You need to keep a reference to the original BufferedInputStream though, but that is obvious.

Well, if you have Caller and Reader class. Caller shouldn't know about the implementation of Reader. In reader's next method:

while scanner has object
   read them ( one object per method's call) 
when objects are done
   close the reader. 

This is a kind of iterator pattern.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!