I
I
IsaevDev2015-07-05 03:53:05
Java
IsaevDev, 2015-07-05 03:53:05

In what situation do I get writable SelectorKey from nio Selektor in Java?

It is clear that I get acceptable and readable in appropriate situations. And when does writable come? At the moment when I write to the channel?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vamp, 2015-08-09
@IsaevDev

Writable is always obtained when there is free space in the output buffer of some socket.
Technically, the write() method just writes data to a special in-memory buffer bound to a network socket. The size of this buffer is controlled by the SO_SNDBUF option . This is an in-memory operation. Real work with the network at this stage does not occur.
Data from the buffer is sent to the network directly by the operating system. The speed at which the buffer is emptied depends on various factors, such as network bandwidth and the performance of the machine on the other end of the wire. If there is at least one free byte in the buffer, then the OP_WRITE flag will be set.
OP_WRITE should only be subscribed to when there is data to send to the remote side, and unsubscribed as soon as the entire chunk of data has been written to the socket. Otherwise, as a result of each call to Selector.select(), you will get a list of all sockets that have free space in the buffer. And since you don’t have data to write, just waste the processor resource.
Figuratively speaking, you subscribe to OP_READ when you want to hear what others have to say, and to OP_WRITE when you yourself have something to say.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question