views:

25

answers:

1

When working with NIO sockets in Java, once I'm connected I can either register for both read and write operations and just do nothing whenever I get a write notification and I have nothing in the outbound buffer, or I can register for read notifications only and re-register for read and write only when something is placed in the outbound buffer. I'm leaning towards the latter but I'm concerned about two things.

  • Would frequent reregistration of interested operations impose any significant performance penalty?
  • Would the reregistration of interested operations in another thread than the one doing the IO operations pose any problem?

EDIT:

Actually another one occured to me. In order to work properly I need to turn on the write registration in the thread that's adding outbound data to the socket, and in the communication thread I need to turn off write registration when the outbound queue is empty. However, this leaves open the following scenario

      IO Thread                                    Other Thread
  Check if buffer empty
                                               Add Item to buffer
                                           Register for write notification 
Turn off write notifications 

The only way I see to avoid this is to turn on thread synchronization on the buffer itself so that modifications to (or checking) the buffer and changing of registration based on that becomes an atomic operation.

A: 

You've basically got it figured out. You want to turn write interest on and off, and synchronization (or single threading) is required.

Another point: as long as you have the lock in your "other thread" you should try writing before you turn on interest. Often the non-blocking write will succeed, and you'll gain efficiency. They will gain you more that you might think.

Darron
I don't see how that can work if I need to preserve the order of bytes output. I'd have to empty the outbound buffer before I can even try sending the data I'm trying to add to the buffer. I'll keep it in mind and will take a look at how feasible that is after I determine the complexity of my sending code.
Jherico
Yes, you have to write in order. But since you have a lock on the buffer you can try writing the first data in the buffer instead of the data you are adding to the end of the buffer (unless it's the only data).
Darron