开发者

How expensive is synchronization?

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?


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜