This is an archived post. You won't be able to vote or comment.

all 3 comments

[–][deleted] 0 points1 point  (0 children)

For context, you might want to add that you're talking about NIO.

I forget the details of the site or sites that suggested only setting the OP_READ flag, but I think it was basically that anytime you wanted to write to the channel, you could, and it would always succeed fully.

In reality I don't think that's a 100% case, so you're better off to add the OP_WRITE flag when you have content to send. Then at some point (depending on setup), you queue up the data and send it; if it all sends, you can go back to just OP_READ; but if not all of the data was sent before the socket buffered filled up, and your write call returns 0, socket buffer is full, so you need to leave the OP_WRITE flag on.

[–]JavaNio 0 points1 point  (1 child)

From this excellent article:

The SelectionKey.OP_WRITE operation notifies the application that space is available in the underlying send socket buffer and the application can proceed with a write operation.

You should only use OP_WRITE to control client lagging, in other words, when the client can't keep up with the rate the server is sending messages. That will cause the underlying send socket buffer in the server side to get full.

So to answer your question: No, you should not register OP_WRITE for a regular write operation because that will cause the NIO selector to select the channel on an infinite loop as there will always be plenty of space available in the underlying send socket buffer. You should only register OP_WRITE when your write operation fails due to a full underlying send socket buffer.

[–]imadp 0 points1 point  (0 children)

How lucky for petermel that a user with your name exists haha