This article mainly introduces the detailed explanation and comparison of Java's NIO and IO. Friends who need it can refer to it
The difference between Java's NIO and IO
NIO is asynchronous IO introduced in JDK1.4. The core part of NIO is three points:
Channel
Comparison between NIO and IO
The difference between NIO and IO, generally speaking In three aspects:Based on Stream Traditional IO based on Buffer
is oriented to byte stream or character stream, but in NIO, we abandoned the traditional IO stream and introduced the concepts of Channel and Buffer. In NIO, I can only read data from a Channel into a Buffer or write data from a Buffer into a Channel. So what is stream-based? In general Java IO operations, we sequentially read one or more bytes from a Stream in a streaming manner, so we cannot change the read data at will. Get the position of the pointer.Unlike IO, which is a sequential operation, in NIO we can read data at any location at will.
Blocking and non-blocking
The various Stream operations provided by Java are blocking. For example, we call a read method to read the contents of a file, Then the thread calling read will be blocked until the read operation is completed. The non-blocking mode of NIO allows us to perform IO operations non-blockingly. For example, we need to read data from the network. In NIO's non-blocking mode, when we call the read method, if there is data at this time, read reads and returns; if there is no data at this time, read returns directly, and Will not block the current thread.selector
selector is a concept unique to NIO. It is the key to why Java NIO can perform IO operations in a non-blocking manner.Through Selector, a thread can monitor the IO events of multiple Channels. When we register a Channel in a Selector, the internal mechanism of the Selector can automatically continuously query (select) for us whether these registered Channels are available. Ready IO events (such as readable, writable, network connection completed, etc.). Through such a Selector mechanism, we can easily use one thread to efficiently manage multiple Channels.
The above is the detailed content of A detailed introduction to the comparison between Java's NIO and IO. For more information, please follow other related articles on the PHP Chinese website!