The difference and comparison between Java NiO and IO

Source: Internet
Author: User
Tags response code

In traditional socket IO, you need to create a thread for each connection, and when the number of concurrent connections is huge, the overhead of the stack memory and CPU thread switching that the thread consumes will be huge. With NIO, you no longer need to create a separate thread for each thread, you can use a thread pool with a limited number of threads, or even a thread for any number of connection services. Because the number of threads is less than the number of connections, each thread does not block the IO operation, and if blocked, some connections are not processed, and NIO provides this non-blocking capability.

The answer to a small number of threads at the same time for large numbers of connections is a ready choice. This is like to eat in the restaurant, every table guests, there is a waiter dedicated to serve you, from you to the restaurant to checkout, so the benefits of the way is good service quality, one-to-one service, VIP Ah, but the shortcomings are also very obvious, high cost, if the restaurant business, at the same time to 100 table guests, it will require 100 The boss had to die of heartache when he got paid, which is the traditional way of connecting a thread.

The boss is a person ah, fine. The boss will have to fathom how can use 10 waiter at the same time for 100 table guests service, the boss found that the waiter in the process of service for guests is not always busy, the guests ordered the dishes, finish the dishes, eating this period of time, the waiter idle down, but this waiter is still occupied by this table guests, Not for other guests, in the words of Huawei Leader, is not full of work. How to use this idle time. The restaurant owner thought of a way, let a waiter (front desk) dedicated to collect the needs of guests, registered, such as the guests come in, the guests order, the guests to check out, are first recorded in order to arrange. Each waiter came here to take a demand, such as a la carte, and took the menu to help guests order. After a good meal, the waiter will come back immediately, collect the next demand, continue to serve other guests. This way the quality of service is not as good as one-to-one service, and when guests have a lot of data may need to wait. But the benefits are also obvious, because the guests are eating at the time the waiter does not have to idle, waiter this time can serve other guests, the original 10 waiter for up to 10 table guests service, now may be 50 tables, 60 guests service.

This type of service differs from the traditional one in two ways:

1, added a role, to have a special responsibility to collect the guests needs of the people. What corresponds to NiO is selector.

2, from the blocking service to non-blocking service, the guests eat when the waiter does not have to be waiting for guests next. Traditional IO operations, such as read (), are blocked until the data arrives when there is no data to read. When no data is readable in NiO, read () returns 0 immediately and the thread does not block.

In NiO, after the client creates a connection, the connection is registered to selector, the equivalent of the guest entering the restaurant, telling the front desk that you want to dine, the front desk will tell you what the number is, and then you may be seated at that table, Selectionkey is the table number. When a table needs to serve, the front desk will record which table needs what service, such as table 1th key dishes, table 2nd to check out, the waiter from the front desk to take a record, according to the records to provide services, finished again to remove a. So the time of service is used most effectively.

Guide:

New I/O class libraries are released in j2se1.4 and above. The NIO library offers some new features: non-blocking I/O, character conversion, buffering, and channels. Both NiO and Io are in the Rt.jar package.

I. Introduction to NIO
The NIO package (java.nio.*) introduces four key abstract data types that work together to address some of the problems in traditional I/O classes.
1. Buffer: It is a linear table structure that contains data and is used for reading and writing. It also provides a special class for I/O operations for memory-mapped files.
2. Charset: It provides the operation of a Unicode string that is mapped to a sequence of bytes and inverse innuendo.
3. Channels: Contains the socket,file and pipe three kinds of pipes, it is actually two-way communication channel.
4. Selector: It centralizes multiple asynchronous I/O operations into one or more line approached (it can be seen as an object-oriented version of the Select () function in Unix or waitforsingleevent () function in Win32).

Second, the traditional way of IO

In the case of network applications, the traditional way to listen to a serversocket is to accept the requested connection to serve it (the service typically involves processing the request and sending a response). Figure one is the life cycle diagram of the server, where the part labeled with the thick black line indicates that I/O blocking occurs.

Figure A

You can analyze each specific step of creating a server. First create the ServerSocket
ServerSocket server=new ServerSocket (10000);
Then accept the new connection request
Socket newconnection=server.accept ();
Calls to the Accept method will cause blocking until ServerSocket accepts a connection request. Once the connection request is accepted, the server can read the request in the client socket.

1InputStream in =Newconnection.getinputstream ();2 3InputStreamReader reader =NewInputStreamReader (in);4 5BufferedReader buffer =NewBufferedReader (reader);6 7Request Request =NewRequest ();8 9  while(!Request.iscomplete ()) {Ten  OneString line =buffer.readline (); A  - Request.addline (line); -}

There are two problems with this operation, first the ReadLine () method of the BufferedReader class causes the thread to block when its buffer is not full, and only if certain data fills the buffer or the client closes the socket, the method returns. Second, it generates a lot of garbage, BufferedReader creates buffers to read data from client sockets, but also creates some strings to store the data. Although BufferedReader internally provides stringbuffer to deal with this problem, all of the strings quickly become garbage that needs to be recycled.

The same problem also exists in the Send response code

1Response Response =request.generateresponse ();2 3OutputStream out =Newconnection.getoutputstream ();4 5InputStream in =Response.getinputstream ();6 7 intch;8 9  while( -1! = (ch =In.read ())) {Ten  One out.write (CH); A  - } -  theNewconnection.close ();

Similarly, read and write operations are blocked and writing one character at a time to the stream can be inefficient, so buffers should be used, but once the buffer is used, the stream generates more garbage.

The traditional way of solving
Blocking I/O is typically handled in Java using threads (a large number of threads). A thread pool is typically implemented to handle requests, and two

Figure II
Threads allow the server to handle multiple connections, but they also cause many problems. Each thread has its own stack space and consumes a bit of CPU time, is expensive, and spends a lot of time on blocking I/O operations, without effectively using the CPU.

Iii. Detailed introduction of NIO

1.  buffer
Traditional I/O is a constant waste of object resources (usually string). New I/O avoids resource wastage by reading and writing data using buffer. A buffer object is a linear, ordered collection of data that contains only a unique data type, depending on its category. The
java.nio.buffer  class description
Java.nio.ByteBuffer contains the byte type. You can read from Readablebytechannel in Writablebytechannel.
Java.nio.MappedByteBuffer contains byte types and is mapped directly in an area of memory
Java.nio.CharBuffer contains character types, cannot write to channel
Java.nio.DoubleBuffer contains double type, cannot write to channel
Java.nio.FloatBuffer contains float type
Java.nio.IntBuffer contains an int type
Java.nio.LongBuffer contains a long type
Java.nio.ShortBuffer contains a short type
You can assign a buffer by calling the allocate (int capacity) method or the Allocatedirect (int capacity) method. Specifically, you can create mappedbytesbuffer by calling Filechannel.map (int mode,long position,int size). Direct Buffer allocates a contiguous block in memory and reads and writes data using local access methods. The non-direct (nondirect) buffer reads and writes data by using the array access code in Java. Sometimes it is necessary to use non-direct buffering such as using any wrap method (such as Bytebuffer.wrap (byte[])) to create a buffer on the basis of a Java array.

2. Character encoding
Storing data into Bytebuffer involves two questions: the order of bytes and the conversion of a character. The Bytebuffer internally handles byte order problems through the Byteorder class, but does not handle character conversions. In fact, Bytebuffer does not provide a way to read and write String.
The Java.nio.charset.Charset handles character conversion issues. It converts character sequences into byte and inverse conversions by constructing charsetencoder and Charsetdecoder.

3. Channels (channel )
You may notice that none of the existing java.io classes can read and write to the buffer type, so the channel class is provided in NiO to read and write buffer. A channel can be thought of as a connection, either to a particular device, to a program, or to a network. The class hierarchy chart for the channel is as follows

Might
Readablebytechannel and Writablebytechannel are used for reading and writing respectively.
Gatheringbytechannel can write data from more than one buffer at once to the channel, whereas Scatteringbytechannel can read the data from the channel at once into multiple buffer. You can also set the channel to be a blocking or non-blocking I/O operation service.
To enable the channel to be compatible with traditional I/O classes, the Channel class provides a static method to create a stream or reader


4. Selector
In the past blocking I/O, we generally know when to read or write to the stream because the method call is returned when the stream is ready. But with non-blocking channels, we need some way to know when the channel is ready. In the NIO package, the design of the selector is for this purpose. Selectablechannel can register a specific event instead of notifying the app when an event occurs, and the channel trace event. Then, when the app calls any of the selection methods on selector, it looks at the registered channel to see if any events of interest occur. Figure IV is an example of a selector and two registered channels

Figure Four
Not all channels are supported for all operations. The Selectionkey class defines all possible operation bits, which will be used two times. First, when the application calls the Selectablechannel.register (Selector sel,int op) method to register a channel, it passes the desired action to the method as the second parameter. Then, once Selectionkey is selected, the Selectionkey's Readyops () method returns the digits of all channels that support the operation. The Selectablechannel Validops method returns the operations allowed for each channel. An operation that is not supported by the registration channel throws an IllegalArgumentException exception. The following table lists the operations supported by the Selectablechannel subclass.

1234 5 6 7 8  9 pipe.sinkchannel Op_write

Four. Illustrative examples

1. Simple Web content Download
This example is very simple, and class Socketchannelreader uses Socketchannel to download the HTML content of a particular Web page.
Package Examples.nio;

 PackageCom.yineng.mycat;ImportJava.nio.ByteBuffer;ImportJava.nio.channels.SocketChannel;ImportJava.nio.charset.Charset;Importjava.net.InetSocketAddress;Importjava.io.IOException;/** * @authorKzfy * @data 2015/12/21*/ Public classsocketchannelreader{PrivateCharset charset=charset.forname ("UTF-8");//creating the UTF-8 character set    PrivateSocketchannel Channel;  Public voidgethtmlcontent () {Try{connect ();            SendRequest ();        Readresponse (); }Catch(IOException e) {System.err.println (e.tostring ()); }finally{            if(channel!=NULL){                Try{channel.close (); }Catch(IOException e) {}}} }    Private voidConnect ()throwsioexception{//Connect to Csdninetsocketaddress socketaddress=NewInetsocketaddress ("Http://www.csdn.net", 80); Channel=Socketchannel.open (socketaddress); //Use the factory method open to create a channel and connect it to the specified address//quite with Socketchannel.open (). connect (socketaddress); Call    }    Private voidSendRequest ()throwsioexception{channel.write (Charset.encode ("get/document\r\n\r\n"));//send GET request to CSDN's document center//using the Channel.write method, it requires parameters of the Charbyte type, using the//The Charset.encode (string) method converts a string.     }    Private voidReadresponse ()throwsioexception{//Read AnswerBytebuffer buffer=bytebuffer.allocate (1024);//Create a 1024-byte buffer         while(Channel.read (buffer)!=-1) {buffer.flip ();//The Flip method is called before the read buffer byte operation. System.out.println (Charset.decode (buffer)); //Convert bytes to strings using the Charset.decode methodBuffer.clear ();//Empty buffer        }    }     Public Static voidmain (String [] args) {NewSocketchannelreader (). Gethtmlcontent (); }}

See http://my.oschina.net/u/1010990/blog/192558

The difference and comparison between Java NiO and IO

Related Article

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.