同步的成本有多高?
我正在使用 java.nio api 编写一个网络应用程序。我的计划是在一个线程上执行 I/O,并在另一个线程上处理事件。但要做到这一点,我需要同步读/写,以便永远不会满足竞争条件。
请记住,我需要同时处理数千个连接,同步是否值得,或者我应该使用单个线程进行 I/O 和事件处理?
I am writing a networking application using the java.nio api. My plan is to perform I/O on one thread, and handle events on another. To do this though, I need to synchronize reading/writing so that a race condition is never met.
Bearing in mind that I need to handle thousands of connections concurrently, is synchronization worth it, or should I use a single thread for I/O and event handling?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你在做什么类型的事件处理?可能的瓶颈在哪里?你还有瓶颈吗?
从最简单的实现开始,一旦了解瓶颈,就可以优化它们。
如果您发现网络 IO 线程读取速度不够快,因为它花费了太多时间处理事件,那么创建一个缓冲队列,与其同步,并让事件处理线程通过队列工作。
您可能想对队列的大小设置限制,这样就不会耗尽内存。如果网络线程即将溢出队列,请让它等待,直到有更多空间。
过早的优化对任何人来说都没有乐趣。
然而,为了回答你的问题,两个线程之间的同步不太可能成为瓶颈,你不应该担心它的开销。
What kind of event handling are you doing? Where is the likely bottleneck? Do you even have a bottleneck?
Start with the simplest implementation and optimize away bottlenecks once you know them.
If you find that your network IO thread isn't reading fast enough because it spends too much time event handling, then make a buffer queue, synchronize to that and have an event handling thread work through the queue.
You might want to set a limit on the size of the queue so you don't end up running out of memory though. If the network thread is about to overfill the queue, have it wait until there's more space.
Premature optimization isn't fun for anyone.
However, to answer your question, synchronization between two threads is not likely going to be a bottleneck and you shouldn't worry about its overhead.
我认为它的效率取决于同步部分的粒度。
I think the efficiency of it will depend on how granular the synchronized section is.