Search code examples
javasocketsobjectinputstream

Better solutions for checking if data is in stream using Java stream functions?


I have an application that needs to read hundreds of socket communications.

I am using a ThreadPool, with a upper limit on the number of threads, to service these sockets. This causes blocking on all threads if the sockets do not have incoming messages.

I am currently using a soTimeout of 100ms to avoid a permanent blocking. I do not like this approach as it might timeout just as it starts receiving input.

Is there anyway other to approach this?

I tried checking with ObjectInputStream.isAvailable(), but that always returns 0, whether there is data in the stream or not.

I can't find any other way to check whether there is data on the stream. This would be ideal, as then I could check if there is data, if not then move on to next stream.


Solution

  • This is exactly the kind of problem NIO frameworks are meant to solve. Unfortunately, using raw NIO is a bit more difficult than using blocking IO. If you can, my recommendation would be to try out a framework like Netty which would ease the job for you.