SocketChannel.read()在异步和同步模式下的差异



我知道java NIO有两种模式,异步模式和同步模式。当我阅读SocketChannel.read()的javadoc时,我得到了以下解释:

Reads a sequence of bytes from this channel into the given buffer. 
An attempt is made to read up to r bytes from the channel, where r is the number of bytes remaining in the buffer, that is, dst.remaining(), at the moment this method is invoked. 
Suppose that a byte sequence of length n is read, where 0 <= n <= r. This byte sequence will be transferred into the buffer so that the first byte in the sequence is at index p and the last byte is at index p + n - 1, where p is the buffer's position at the moment this method is invoked. Upon return the buffer's position will be equal to p + n; its limit will not have changed. 
A read operation might not fill the buffer, and in fact it might not read any bytes at all. Whether or not it does so depends upon the nature and state of the channel. **A socket channel in non-blocking mode, for example, cannot read any more bytes than are immediately available from the socket's input buffer; similarly, a file channel cannot read any more bytes than remain in the file. It is guaranteed, however, that if a channel is in blocking mode and there is at least one byte remaining in the buffer then this method will block until at least one byte is read.** 
This method may be invoked at any time. If another thread has already initiated a read operation upon this channel, however, then an invocation of this method will block until the first operation is complete. 

让我感到困惑的是异步和同步读取的解释。是的,在异步模式下,它会立即读取缓冲区中已经存在的内容并返回。但在同步模式下,它不一样吗?如果缓冲区中有东西,为什么不读取它并立即返回?等什么?

如果缓冲区中有东西,为什么不读取它并立即返回?

我想你理解错了。正如文档中所说的int读取(ByteBuffer dst)

字节要传输到的缓冲区。

通道读取字节并将其写入缓冲区。

但是,可以保证的是,如果信道处于阻塞模式,并且缓冲区中至少还有一个字节,则此方法将阻塞,直到读取至少一个字节为止。

CCD_ 1表示缓冲器仍有空闲空间。函数boolean hasRemaing()和int remaining()用于检查这一点。

等什么?

等待从通道读取一些字节或到达流的末尾。阻止通道上的读取无法返回0。

最新更新