IO classification of Java in the Java NIO

Foreword 

The previous two articles ( understand I / O model (a) Java NIO's , the Java NIO understanding of the I / O model (b) ) describes the mechanism IO, and the contents of several IO model, as well as related to the design mode. The write some content closer to the actual number, and finally comes to the variety of the IO Java. I also learn while understanding, write the wrong place, welcome little friends pointed and additions.

IO classification in Java

BIO

BIO refers Blocking IO in JDK1.0 when he was introduced, until JDK1.4 Java has been the only way to IO. Its main implementation is that a thread executes a request, if a large amount of data would have been occupied by a thread request, or a request to do nothing, will also take up a thread, so that when a client requests the number is increased, the the server thread count also followed increases, and eventually it will lead to the collapse of the server CPU. Of course, you can use the thread pool to reduce the pressure of the CPU, but after all, the thread pool is not a problem in essence (long link, the thread pool size, and deny policy must take into account, among other factors).

Whether or local network connection read operations are output in this way. I do not cite specific examples of the (after all, this is not the focus of BIO).

NIO

Java NIO in fact, is the use of multiple I / O multiplexing model , the previous article has introduced the principle, but before understanding the Java NIO, or introduce some basic concepts of Java NIO: Channel (Channel), buffer (buffer), selector (selector).

Channel (Channel)

Channel can be understood as exchange pipes, and Java IO various Stream (InputStream, OutputStream, etc.) a grade, but Channel in both directions, while the Stream is unidirectional. The role of channels are channels data into or out various I / O source, to read and writeable.

In the Java class hierarchy Channel is quite complex, and many have multiple interfaces optional. But also a few commonly used.

FileChannel

DatagramChannel

SocketChannel

ServerSocketChannel

FileChannel can read and write to the file, the DatagramChannel UDP protocol may be used to read and write data, to the SocketChannel TCP protocol to read and write to both ends of the network, ServerSocketChanel able to listen to the client initiates the TCP connection, and for each TCP create a new connection SocketChannel to read and write data.

Buffer (buffer)

Buffer is an efficient data container, in NIO all data must pass through buffer operations, and this point is different from BIO, BIO directly writes the data in the Stream object. Because the design Stream object data is sequentially transferred a byte by byte. Although for performance reasons, you can also pass a byte array, but the basic concept is the transfer of a data byte by byte. The contrast that channel, the channel sends a data block buffer, and in accordance with the basic concept of the channel is a block of data to read and write a data block. It can also be understood as a byte array buffer, designed to store the ready of access and byte.

As shown below:

 

As shown above, both the client to send and receive data, or the server and receiving the corresponding data, the data operation is performed from the buffer.

In addition to Java, boolean, all the basic data types have specific Buffer subclasses:

ByteBuffer, CharBuffer, DoubleBuffer, FloatBuffer, IntBuffer, LongBuffer, ShortBuffer . Network program almost only use ByteBuffer, but occasionally use other types of programs to replace ByteBuffer.

In addition to data list, each buffer record four key portion of the information. Regardless of the type, we have the same methods to get and set these values:

  • Position (position)

The buffer will be read or written to the next location. This position starts counting from zero, is equal to the maximum size of the buffer. Get and set by the following two methods.

public final int position();
public final Buffer position(int newPosition);
  • Capacity (capacity)

The maximum number of buffers that can be saved. When you create a buffer capacity value is set, then it can not be changed.

It can be read by the following method:

public final int capacity();
  • Limit (limit)

The end of the buffer can access the location data. They do not change the limit, you can not read / write data beyond this position, even if the buffer has a greater capacity to no avail. Put limits can use the following two to get and set.

public final int limit();
public final Buffer limit(int newLimit);
  • Mark (mark)

The index specified by the client buffer. Flag may be set by calling the current position mark (). Call reset () can set the current position as a location identified.

public final Buffer mark() ;
public final Buffer reset();

If the position is set lower than the conventional tag, the tag is discarded.

InputStream reading different buffer is actually read data in the buffer does not change in any way. You can only be set forward or backward position, allowing a specific position to start reading from the buffer. Similar procedures can be adjusted limits, thereby controlling the end of the data to be read. Only capacity is fixed.

Selector (selector)

Java NIO Selector is the most important part of the role Selector is to use a single thread to handle poll of registered Channel, which Channel once the data is ready, it can be dealt with.

As shown below:

Use Selector, first to register Channel Selector, and then call it a select () method, which would have been blocked to a registered Channel events ready. Once the select () method returns, the thread may process the event, such as entering a new connection, the data reception and the like.

Method Selector class does not register a new channel, register () method is declared in SelectableChannel class. SelectableChannel class is to achieve self-Channel interface, it supports to register Channel Selector in.

SelectableChannel provides two methods of registering Channel:

public abstract SelectionKey register(Selector sel, int ops, Object att) throws ClosedChannelException;
public final SelectionKey register(Selector sel, int ops) throws ClosedChannelException;

The first parameter is the channel selector which want to register. The second parameter is a named constant SelectionKey class identifying registered operation.

SelectionKey name defines four-bit constant, the user selects the type of operation:

SelectionKey.OP_READ;
SelectionKey.OP_WRITE;
SelectionKey.OP_CONNECT;
SelectionKey.OP_ACCEPT;

When a plurality of channels operating in the same concern a selector, the user need only bits "or" operator to a combination of these constants.

channel.register(selector,SelectionKey.OP_READ | SelectionKey.OP_WRITE);

The third parameter is optional, represents a bond of attachment. This parameter is usually stored in a user link status, for example: if you want to implement a Web server, or may want to attach a FileInputStream FileChannel, or the flow passage is connected to a local file server to the client.

example:

Copy the file read and write operations, it can be used to illustrate a general process of NIO.

public static void copyFileByNIO(String src,String dst) throws IOException {

        // declare the source and target files 
        RandomAccessFile aFile = new new RandomAccessFile (src, "rw" );
        RandomAccessFile bFile = new RandomAccessFile(dst, "rw");

        // obtain transmission channel Channel 
        FileChannel inChannel = aFile.getChannel ();
        OutChannel FileChannel = bFile.getChannel ();
         // get the container Buffer 
        the ByteBuffer Buffer = ByteBuffer.allocate (1024 );
         the while ( to true ) {
             // determines whether the file has been read 
            int EOF = inChannel.read (Buffer);
             IF (EOF = -1 = ) {
                 BREAK ;
            }
            // Reset bit = 0 buffer of position, position limit = 
            buffer.flip ();
             // start writing 
            outChannel.write (buffer);
             // finish To reset the buffer, 0 = reset position, limit = Capacity 
            buffer .clear ();
        }
        inChannel.close();
        outChannel.close();
        aFile.close();
        bFile.close();
    } 

AIO

The AIO is not introduced, I want to single out a follow-up to the full introduction AIO.

Guess you like

Origin www.cnblogs.com/jimoer/p/11575610.html