Non-blocking socket writes in Java versus blocking socket writes

后端 未结 2 732
暖寄归人
暖寄归人 2021-01-05 15:43

Why would someone prefer blocking writes over non-blocking writes? My understanding is that you would only want blocking write if you want to make sure the other side got th

相关标签:
2条回答
  • 2021-01-05 16:18

    The problem with non blocking writes is that you may not have anything useful to do if the write is incomplete. You can end up with loops like

    // non-blocking write
    while(bb.remaining() > 0) sc.write(bb);
    

    OR

    // blocking write
    sc.write(bb);
    

    The first can burn CPU and the second might be more desirable.

    The big problem is reads. Once you decide whether you want blocking or non-blocking reads, your writes have to be the same. Unfortunately there is no way to make them different. If you want non-blocking reads, you have to have non-blocking writes.

    0 讨论(0)
  • 2021-01-05 16:25

    My understanding is that you would only want blocking write if you want to make sure the other side got the TCP packet once the write method returned

    Your understanding is incorrect. It doesn't ensure that.

    Blocking writes block until all the data has been transferred to the socket send buffer, from where it is transferred asynchronously to the network. If the reader is slow, his socket receive buffer will fill up, which will eventually cause your socket send buffer to fill up, which will cause a blocking write to block, blocking the whole thread. Non-blocking I/O gives you a way to detect and handle that situation.

    0 讨论(0)
提交回复
热议问题