Java NIO, javanio

Source: Internet
Author: User

Java NIO, javanio
I. Overview

Since JDK1.4, Java provides a series of New features for improved input/output processing, collectively referred to as NIO (New I/O ). Many new classes are added for processing Input and Output. These classes are stored in java. nio package and sub-package, and for the original java. many classes in the io package are rewritten, And the NIO-compliant function is added. NIO uses a memory ing file to process input and output. NIO maps a region of a file or file to the memory, so that the file can be accessed just like the memory.

  

Channel, Buffer, and Selectors are two core objects in NIO.

Channel is a simulation of traditional I/O systems. In NIO, all data must be transmitted through Channel. The biggest difference between it and traditional I/O is that it provides a map method, through which "one piece of data" can be directly mapped to the memory, if traditional I/O is stream-oriented, NIO is block-oriented.

Buffer can be understood as a container. In essence, it is an array. All objects sent to the Channel must be placed in the Buffer first, and data read from the Channel must be read to the Buffer first.

The server and client each maintain a management Channel object called Selector, which can detect events on one or more channels. Take the server as an example. If the selector on the server registers a read event, the client sends some data to the server at a certain time point, blocking I/O will call read () method to read data in a blocking manner, while the NIO server will add an event to the Selector, and the processing thread on the server will poll the access Selector. If an event of interest arrives when the selector is accessed, the processing thread will be blocked until the events of interest arrive.

IO VS NIO

NIO allows you to manage multiple channels with only one or several single threads, but it is more complicated to parse data than to read data from a blocked stream.

If you need to manage thousands of connections opened at the same time, these connections send only a small amount of data each time, such as chat servers, the server implementing NIO may be an advantage.

If you have a small number of connections that use very high bandwidth and send a large amount of data at a time, the typical I/O server implementation may be more compatible.

Ii. Buffer Zone

Buffer is a linear finite sequence of elements of a specific basic type. In addition to content, the basic attributes of Buffer also include capacity, limits, and locations:

  • Capacity: The number of elements it contains. The buffer capacity cannot be negative and cannot be changed.
  • Restriction: it is the first index of the element that should not be read or written. The buffer limit cannot be negative or greater than its capacity.
  • Location: The index of the next element to be read or written. The position of the buffer cannot be negative and cannot exceed the limit.

Buffer is mainly used to load data and then output data. At the beginning, the position of the Buffer is 0, the limit is capacity, and the program calls put to continuously put data into the Buffer. Each time some data is put, the position response moves backward. After the Buffer is loaded into the data, call the filp method. This method sets limit to the position where the position is located and set the position to 0, in this way, when reading data from the Buffer, it always starts from 0. After reading all the data just loaded, it ends.

To read and write data using Buffer, follow these four steps:

  • Write Data to Buffer
  • Call the flip () method
  • Read data from Buffer
  • Call the clear () or compact () method

Eg:

Public class TestMain {public static void main (String [] args) {CharBuffer buff = CharBuffer. allocate (5); System. out. println ("buff. capacity = "+ buff. capacity (); System. out. println ("buff. position = "+ buff. position (); System. out. println ("buff. limit = "+ buff. limit (); buff. put ('A'); buff. put ('B'); System. out. println ("add elements to Buffer --------"); System. out. println ("buff. capacity = "+ buff. capacity (); System. out. println ("buff. position = "+ buff. position (); System. out. println ("buff. limit = "+ buff. limit (); buff. flip (); System. out. println ("after calling the filp function ------------"); System. out. println ("buff. capacity = "+ buff. capacity (); System. out. println ("buff. position = "+ buff. position (); System. out. println ("buff. limit = "+ buff. limit (); System. out. println (buff. get (0); // use the absolute operation to obtain the element at the zero position without changing the position value }}

Running result:

Among them, the source code of filp (), for example, indicates that the Buffer is filled with data, position is returned to the starting point, and limit is set to position, which is equivalent to sealing up the storage space without data in the Buffer, avoid reading null values.

 public final Buffer flip()
{ limit = position; position = 0; mark = -1; return this; }

Another point worth mentioning is the clear () method. The source code is as follows:

public final Buffer clear() {        position = 0;        limit = capacity;        mark = -1;        return this; }

Obviously, this method does not actually clear the buffer. It only sets the position back to the starting position. In this case, you can still get the specified position element through the get method, and then set the limit to capacity, it seems that the buffer is cleared. The purpose of this operation is not to create a buffer for each read/write operation, which will reduce the performance. Instead, to reuse the current buffer, clear the buffer before reading it again.

For each non-boolean basic type, this class corresponds to a subclass.

Each subclass defines two types of acquisition and placement operations:

Relative: reads or writes data from the current location of the Buffer, and then increases the value of the location according to the number of processed data.

Absolute: read or write data directly to the Buffer Based on the index. When you access the Buffer in absolute mode, the value in position is not affected.

3. Channels

Channels are similar to traditional stream objects, but there are two main differences between them:

A Channel represents an open connection to an entity, such as hardware devices, files, network sockets, or program components that can perform one or more different I/O operations. All channels are not created through the constructor, but are returned through the getChannel methods of the traditional nodes InputStream and OutputStream.

The three most commonly used methods in a Channel are map, read, and write. The map method is used to map some or all data of a Channel to ByteBuffer, the read or write methods have a series of reloads, which are used to read data from the Buffer or write data to the Buffer. Eg:

Public class TestMain {public static void main (String [] args) throws UnknownHostException, IOException {FileChannel outChannel = null; File file = new File ("E: \ hello.txt "); fileInputStream inputStream = new FileInputStream (file); FileChannel fileInChannel = inputStream. getChannel (); // map all data in FileInChannel to ByteBuffer MappedByteBuffer buffer = fileInChannel. map (FileChannel. mapMode. READ_ONLY, 0, file. length (); Charset charset = Charset. forName ("GBK"); // create a FileBuffer in the form of a file output stream to control output outChannel = new FileOutputStream ("E: // hello_Copy.txt "). getChannel (); outChannel. write (buffer); buffer. clear (); CharsetDecoder decoder = charset. newDecoder (); CharBuffer charBuffer = decoder. decode (buffer); System. out. println (charBuffer); inputStream. close (); fileInChannel. close (); outChannel. close ();}}

Running result:

  

In the above Code, the FileChannel obtained from FileInputStream can only be read, while the FileChannel obtained from FileOutStream can only be written. The program first maps all the data in the specified Channel to ByteBuffer, and then directly writes all the data in the entire ByteBuffer to an output FileChannel. This completes file replication.

Another easier way to copy files is to directly transfer data from one channel to another. Eg:

public class TestMain{    public static void main(String[] args) throws UnknownHostException, IOException    {        RandomAccessFile fromFile = new RandomAccessFile("E://hello.txt", "rw");          FileChannel      fromChannel = fromFile.getChannel();          RandomAccessFile toFile = new RandomAccessFile("E://toFile.txt", "rw");          FileChannel      toChannel = toFile.getChannel();          long position = 0;          long count = fromChannel.size();          toChannel.transferFrom(fromChannel, position, count);          fromFile.close();        toFile.close();    }}
Iv. Selector

Selector is a component that can detect one or more NIO channels in Java NIO and determine whether the channel is ready for read/write events.

You can call this open () method to create a selector. This method uses the default selector provider of the system to create a new selector. It remains open until the selector is closed by the close () method of the selector.

The SelectionKey object indicates that the SelectionKey can be registered with the selector. The selector maintains three selection key sets:

  • Key set: indicates the registration of the current channel to this selector. This set is returned by the keys method.
  • Selected key set: during the previous selection operation, check whether the channel of each key is at least ready for an operation identified by the related operation of the key. This set is returned by the selectorKeys method.
  • Canceled key set: a set of keys that have been canceled but whose channels have not been canceled. You cannot directly access this set.

When registering a channel through the register Method of a channel, a key is added to the selector's key set, removing the canceled key from the key set during the selection operation.

When used with Selector, the Channel must be in non-blocking mode. This means that FileChannel and Selector cannot be used together, because FileChannel cannot be switched to non-blocking mode. All socket channels are supported.
The second parameter of the register () method. This is an "interest set", which means what events are interested in listening to channels through Selector. You can listen to four different types of events:

  • Connect
  • Accept
  • Read
  • Write

The channel triggers an event, which means the event is ready. Therefore, a channel successfully connects to another server and is called "connection ready ". A server socket channel is ready to receive incoming connections ". A channel with readable data can be said to be "Read-ready ". The channel waiting for Data Writing can be said to be "ready to write ".
These four events are represented by four constants of SelectionKey:

  • SelectionKey. OP_CONNECT
  • SelectionKey. OP_ACCEPT
  • SelectionKey. OP_READ
  • SelectionKey. OP_WRITE

If you are interested in more than one event, you can use the bitwise OR operator to connect constants.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.