使用 Java 流函数检查数据是否在流中的更好解决方案?

发布于 2024-11-26 23:11:47 字数 316 浏览 4 评论 0 原文

我有一个应用程序需要读取数百个套接字通信。

我正在使用具有线程数量上限的线程池来为这些套接字提供服务。如果套接字没有传入消息,这会导致所有线程阻塞。

我目前使用 100 毫秒的 soTimeout 来避免永久阻塞。我不喜欢这种方法,因为它可能会在开始接收输入时超时。

还有其他方法可以解决这个问题吗?

我尝试使用 ObjectInputStream.isAvailable() 检查,但无论流中是否有数据,它总是返回 0。

我找不到任何其他方法来检查流上是否有数据。这将是理想的,因为这样我可以检查是否有数据,如果没有,则继续到下一个流。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

︶葆Ⅱㄣ 2024-12-03 23:11:47

这正是 NIO 框架要解决的问题。不幸的是,使用原始 NIO 比使用阻塞 IO 更困难一些。如果可以的话,我的建议是尝试 像 Netty 这样的框架,这会减轻你的工作负担。

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.

伊面 2024-12-03 23:11:47

你可以给蔚来一个机会。
使用Selector和SocketChannels来等待数据,而不是为每个套接字创建线程。

选择器

SocketChannel

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

Selector

SocketChannel

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文