开发者

How to make readInt() block on input byte stream?

I have an input stream coming form a blackbox (say B). All the messages coming in from this stream are serialized binary data and each message starts with a four byte int. Most of it is logging data and runs 24 hrs a day. I read these four bytes using readInt() method. Now, ocasionally, the main thread would exit with EOFException and crash the program.

After researching on this, I found that it happens when there are less than four bytes in the input stream at the time of readInt(). My guess is that the buffer is not filling in fast enough between successive reads. Some of the possible solutions I am thinking of include checking available() before reading (consumes too many cycles considering the amt of data) or restart when exception occurs (sounds li开发者_开发技巧ke poor programing). If only I could block using readInt(), it would be the best way, I think. I've looked at implementation of readInt() but again it boils down to blocking with read().

Anyone knows of a better solution?


Any blocking call down the call hierarchy is "bound" to make all the calls up the chain blocking as along as both calls are part of same thread of execution. The readInt method of DataInputStream makes four calls to the read method of the underlying input stream which will surely block as long as the data is not made available hence your fear of "buffer doesn't fill in fast enough" doesn't seem to be logical.

I have encountered these kind of exceptions in cases where either the server process dies or or drops the connection in which case the client ends up reading a -1 and throws an exception. Are you gobbling any sort of exceptions in your client/server code? Do your logs show anything suspicious?


I believe that you are using DataInputStream. That class throws EOFException in situation when the stream which it wraps, returns -1 from the read() method (which actually blocks until input data is available).

I suppose, you should have a look why the main stream's read returns with -1 in the first place.


The basic InputStream interface requires blocking reads, the EOFException you get is thrown when the readInt() encounters the end of stream marker, since returning the incomplete int would be a bad idea it throws the End Of File Exception.

The EOFException is thrown because the other end of the stream reached its end,has been closed or is no longer connected. You should check if the blackbox terminates the connection.

Since the stream is network based your socket may have a timeout set, if this is the case try changing the SOTimeout value of the socket.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜