java - BIO, NIO, AIO

What's java IO is implemented?

Java programs for data input / output operation are the "flow" of the way, java io is used to operate on the data.

Three types of JAVA IO

Synchronous blocking the BIO
NIO synchronous non-blocking
asynchronous non-blocking AIO

Sync: When synchronous IO, Java IO deal with their own reading and writing.
Asynchronous: when using asynchronous IO, Java OS will be entrusted to handle IO read and write, you need to pass data buffer address and size of the OS, OS needs to support asynchronous IO operations API.
Blocking: When to use blocking IO, Java has been blocked call will write to complete before returning.
Non-blocking: When using a non-blocking IO, if you can not read and write Java call will return immediately, when the IO event dispatcher will inform the reader can continue to read and write, read and write continuously loop until completion.

1.BIO (synchronous blocking)

When a data source IO operations, other operations can not be performed on this stream data source, you must play with other operations, other operations on the data stream in order to operate.
Why is synchronous blocking?
It is actually the server to create a ServerSocket, then the client is using a Socket to connect to the server-side ServerSocket, ServerSocket receives a connection request to create a Socket to communicate and talk to a thread that Socket. Next the client and the server proceeds blocking communication, the client sends a request, response is returned after the end of processing Socket.
Each time a client access, requires the server creates a thread to service the client
(1) read a single byte of the byte stream (Stream are ending)
the input stream InputStream: reading data from an external data source to internal procedures.
Output stream OutputStrem: Output from the program data to an external data source

InputStream (input stream)
ByteArrayInputStream (array operations)
the PipedInputStream (pipeline operation)
FilterInputStream (filter input stream, byte stream decorating)
Bu FF eredInputStream (byte stream operation with a buffer)
DataInputStream (basic data type of the operation)
the FileInputStream (file operation )
the ObjectInputStream (object action, serialization)
OutputStream (output stream)
ByteArrayOutputStream (array operations)
the PipedOutputStream (pipelining)
of FilterOutputStream (filter output streams, decorating byte stream)
Bu FF eredOutputStream (byte stream operation with a buffer)
the DataOutputStream ( basic data type of the operation)
PrintStream (print)
a FileOutputStream (file operation)
ObjectOutputStrem (object action, deserialize)

(2) Read a single character character stream (Reader, the end of the character stream are Wirter)
Reader (input stream)
CharArrayReader from (array operations)
a PipedReader so (pipeline operation)
FilterReader (filtration flow, decorating the character stream)
Bu eredReader FF (with buffered character streams)
the InputStreamReader (commutations)
the FileReader (file operation)

Wirter (output stream)
CharArrayWirter (array operations)
PipedWirter (pipeline operation)
FilterWirter (filtration flow, the character stream decorating)
Bu FF eredWriter (character streams with buffer)
the OutputStreamWriter (commutations)
FileWriter (file operation)
the PrintWriter (Print)

Simple file operation on the stream file: Sample Code

Read the contents of a text document

package file;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class BIO {
    public static void  main (String args[]) throws IOException {
        //根据指定路径创建一个文件句柄
        File file =new File( "C:\\Users\\Lenovo\\Desktop\\hello.txt");
        FileInputStream fis = null;
        try {
          //打开此文件的操作流程
            fis = new FileInputStream(file);
            byte[] bytearr = new byte[128];
         //读取指定长度的数据
            fis. read(bytearr);
            String str = new String (bytearr);
            System.out.println(str);
            
		 //打开输出流 
            FileOutputStream fos = new FileOutputStream(file);
            String   string=  new String("alaaalalalalalala");
         //将文本文档的内容由hello改变成alaaalalalalalala
            fos.write(string.getBytes());
            fos.close();
		
        }
        catch (Exception e){
            e.printStackTrace();
        }
        finally {
            fis.close();
        }
    }
}

Operation will then use BufferedInputStream FileInputStream fis = null; change BufferedInputStream fis = null;
the fis = new FileInputStream (file); changed fis = new BufferedInputStream (new FileInputStream ( file));
Here Insert Picture Description
Here Insert Picture Description

2.NIO (synchronous non-blocking)

Why is synchronous non-blocking NIO why?
Because no matter how many clients can access the server, client access and does not consume a thread, it will only create a connection and then registered to the selector up, so you can shop and go to other things you want to do the other, a selector thread continuously polls all connected to the socket, found the event to inform you, and then you start a thread to process a request, then the process is non-blocking. But this treatment process, you still must first read data, process, and then returned, this is a synchronous process.

NIO three core concepts :
Buffer (Buffer)
Channel (channel)
Selector (selector)
1. Buffer (Buffer)
to write data to a file by NIO or network, and the network or the data read from the file at this time out buffer needs to be done by the buffer.
Buffer using the following general steps: Buffer write data to, invoke Flip () method reads the data from Buffer, call clear () method or a compact () method.
Buffer contains the data to be written to or read out just now

Each Java primitive types (except Boolean) corresponds to one kind of buffer, as follows:
the ByteBuffer
CharBuffer
ShortBuffer
IntBuffer
LongBuffer
FloatBuffer
the DoubleBuffer
use buffer, the buffer size to be defined.
Here Insert Picture Description
2. The read-write channel (Channel)
Channel is an object, through which data can be written and read. Take NIO with the original I / O make a comparison, the channel is like a
stream. This channel is inserted to buffer read and write data. Reading and writing data through the network Channel.

Channel Four achieve:
FileChannel: data is read from the file.
DatagramChannel: to read or write data from the UDP networks.
SocketChannel: to read or write data from the TCP network.
ServerSocketChannel: allows you to listen for connections from TCP, like server. Each connection will have a SocketChannel generated.

3.Selector Selector
Selector Selector can monitor a plurality of channels of interest Channel things (read, write, accept (receiving server), connect, to achieve a plurality of thread management Channel, save resource consumption of the thread context switching only .Selector energy management channel non-blocking, FileChannel is blocked, can not manage.

Here Insert Picture Description

3.AIO (asynchronous non-blocking)

NIO AIO with similar, but NIO to make their own polling to determine the operating system to complete the state, and AIO, then the operating system to the client callback interface, to tell you the operation is complete.

Why AIO is asynchronous non-blocking?
Following the adoption of AIO after initiating a file IO operations, you can immediately return to do other thing, then you do not control the operating system finished the job himself IO, tell you that ok.
When you AIO based on the api to read and write files, when you initiate a request later, all that remains is to write the operating system when completed, the operating system will come to your callback interface, to tell you the operation is complete. During this period do not need to wait, do not need to go to a polling judge to complete the operating system of the state, you can shop and go to other things. Synchronization is their own polling had to take the initiative to the operating system, the operating system is asynchronous in turn inform you. So it is, AIO is asynchronous non-blocking.

Published 59 original articles · won praise 11 · views 2241

Guess you like

Origin blog.csdn.net/qq_41219586/article/details/104517281