Search code examples
javainputstreambufferedinputstreamdatainputstream

Java DataInputStream vs. BufferedInputStream


I'm looking for an efficient solution to receive and process asynchronous messages (of varying size) from a socket connection to a server. It is a good amount of bandwidth coming over (maybe 250 kB/s steady state, and can have short bursts up to 1 MB/s). Currently I'm using a DataInputStream, but during busy moments I get disconnected (the server disconnects a client if the queue backlog grows too large).

Can anyone confirm if a BufferedInputStream may work better? I've read that it will retrieve chunks of data at a time, rather than byte by byte, so there are fewer OS calls.

Thanks!


Solution

  • It does retrieve chunks at a time, and it could have fewer OS calls, but this won't help if you aren't calling read fast enough to service the backlog. It won't read the next chunk until you fully read through the chunk it prefetched.

    Probably the best thing to do is to constantly stay on top of the InputStream (read it whenever it has something to read) and do any other processing later or in a another (lower priority) thread.