views:

70

answers:

2

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?

+1  A: 

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.

Ben S
@Ben: I suppose you meant "**shouldn't** worry about its overhead"
Eyal Schneider
yes, sorry, fixed now.
Ben S
I would like to decouple reading/writing and event handling, but if synchronization is too expensive, I don't think it's worth it.Imagine synchronizing thousands of times every second; would that cause too much stress?
someguy
Why do you want to decouple it? Do you know that you need to? Have you tried it? There's no way for us to know what the performance impact is going to be with your specific implementation. Synchronizing thousands of times per second does not sound stressful. Your OS is doing that in the background constantly already.
Ben S
A: 

I think the efficiency of it will depend on how granular the synchronized section is.

Wifi Cordon