开发者

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.


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.


You can give NIO a chance. Use Selector and SocketChannels to wait for data instead of creating thread for each socket.

Selector

SocketChannel

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜