Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
514 views
in Technique[技术] by (71.8m points)

java - When is InputStream.available() useful?

When is InputStream.available() or BufferedInputStream.available() useful in socket programming in Java?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

My take is that method is not useful unless you know how good the "estimate" is. And in the case of a stream connected to a socket, the estimate cannot be reliable in all cases.

The problem is that the method's return value does not distinguish between the cases where you have reached the end of stream on the socket, and where there are no characters currently available on the socket but more might be delivered. Both could return zero ... according to the javadoc.

This uncertainty renders the method pretty much useless.

  • In the socket case (and similar ones), the available() method doesn't really tell you whether to read or not if the result is zero. And if you make the wrong choice, you will either block when you don't mean to, or never discover that the socket has actually been closed. Either of those could be bad.

  • In other cases (like reading from a local file), there are other ways of finding whether the read is likely to block. Besides, the read is unlikely to block for long anyway, so there's usually not a great deal of point in avoiding blocking.

  • Finally, in some cases I think that you could get a non-zero response and have the read call block anyway. (I'm thinking of files on remote mounted file systems ... and the possibility of the remote server freezing when you try to read.)

The bottom line is that available() is documented as returning an estimate. The javadoc provides no guarantees of how reliable that estimate will be under all possible circumstances, and indeed in some circumstances the estimate cannot be accurate because that would require knowing what a remote server is going to do.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...