'Does java nio read/write file actually non-blocking io?
I'm learning about non-blocking i/o terms. Mainly, I'm learning java Nio. I'm trying to understand non-blocking i/o better and observe how it works in the implementation with Java Nio.
I read a dozen questions and answers related to the non-blocking i/o term and the non-blocking i/o by using java Nio.
I see a following similar statement everywhere.
Non-blocking IO does not wait for the data to be read or written before returning. Java NIO non-blocking mode allows the thread to request writing data to a channel, but Non-blocking IO does not wait for the data to be read or written before returning.
I tried to illustrate the statement with an example java code that reads a file's content using Nio. However, the thread is still blocked at the channel's read() method.
System.out.println("Thread-" + Thread.currentThread().getName()
+ "-" + Thread.currentThread().getId());// Thread-main-1
String filePath = "./resources/nio-demo.txt";
FileInputStream fis = new FileInputStream(new File(filePath));
FileChannel fileChannel = fis.getChannel();
ByteBuffer buf = ByteBuffer.allocate(102400);
int bytesRead = fileChannel.read(buf);
System.out.println(buf.position()); //check how many bytes are written to the buf, always 102400
while (bytesRead != -1)
{
buf.flip();
while (buf.hasRemaining())
{
System.out.print((char) buf.get());
}
buf.clear();
bytesRead = fileChannel.read(buf);
}
fis.close();
As I understand, after triggering the read() method, the thread will execute the following line of code. It doesn't matter if the buf is full of data or not. But here, the thread is blocked until the buf is complete and continues the process sequence.
The above example reads a file about 300M with buf is 102400.
The situation confused me much; perhaps I misunderstood non-blocking i/o with java Nio.
Could you please help me explain this situation?
How does java Nio achieve purely non-blocking i/o with only one thread?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
