Java 中的非阻塞套接字写入与阻塞套接字写入 [英] Non-blocking socket writes in Java versus blocking socket writes

查看:42
本文介绍了Java 中的非阻塞套接字写入与阻塞套接字写入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么有人更喜欢阻塞写入而不是非阻塞写入?我的理解是,如果您想确保在 write 方法返回后另一方收到 TCP 数据包,您只会想要阻塞 write,但我什至不确定这是否可能.您将不得不刷新并且刷新必须刷新底层操作系统写入套接字缓冲区.那么非阻塞套接字写入有什么缺点吗?就性能而言,拥有一个大的底层写套接字缓冲区是一个坏主意吗?我的理解是,底层套接字写入缓冲区越小,您就越有可能遇到慢速/有问题的客户端,并且必须在应用程序级别丢弃/排队数据包,而底层套接字缓冲区已满并且 isWritable() 返回 false.

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 the TCP packet once the write method returned, but I am not even sure that's possible. You would have to flush and flush would have to flush the underlying operating system write socket buffer. So is there any disadvantage of non-blocking socket writes? Does having a large underlying write socket buffer a bad idea in terms of performance? My understanding is that the smaller the underlying socket write buffer the more likely you will hit slow/buggy client and have to drop/queue packets in the application level while the underlying socket buffer is full and isWritable() is returning false.

推荐答案

我的理解是,如果您想确保在写入方法返回后另一方收到 TCP 数据包,您只会希望阻塞写入

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.

阻塞写入阻塞直到所有数据都传输到套接字发送缓冲区,然后从那里异步传输到网络.如果reader速度慢,他的socket接收缓冲区就会被填满,最终会导致你的socket发送缓冲区填满,从而导致一个blocking write阻塞,阻塞整个线程.非阻塞 I/O 为您提供了一种检测和处理这种情况的方法.

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.

这篇关于Java 中的非阻塞套接字写入与阻塞套接字写入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆