Java basics-New I/O technology (NIO) and basics nio

Source: Internet
Author: User

Java basics-New I/O technology (NIO) and basics nio
Before JDK1.4, I/O input/output processing is called the old I/O processing. Beginning with JDK1.4, java provides a series of improved new input/output features, these functions are called new I/O (new I/O) and many NEW classes are added for processing input/output.Java. nio package and sub-PackageIn addition, many classes in the original java. io package are rewritten based on NIO, and new functions to meet new I/O requirements are added. Main differences between Java NIO and IO

IO NIO
Stream-oriented
Buffer-oriented
Blocking IO
Non-blocking IO
None
Selector
Buffer-oriented)

In the whole Java I/O, operations are carried out in a buffer, greatly improving the operation performance.

Operation

There are a series of status variables in the Buffer, which may be interpreted as writing or reading, and three values are used to indicate the status of the Buffer when the Buffer is enabled.

  • Position: indicates the operation pointer for reading or writing data in the next buffer zone. This pointer changes when data is not written to the buffer zone China. The pointer is always placed after the last element written. That is, if data is written in four locations, the posotion points to the 5th locations.
  • Limit: indicates how much data can be stored or read, position <= limit
  • Capacity: Maximum buffer capacity, limit <= capacity. This value is set when the buffer is allocated. Generally, it does not change.

Create a buffer:

Import java. nio. intBuffer; public class IntBufferDemo {public static void main (String args []) {IntBuffer buf = IntBuffer. allocate (10); // prepare a buffer of 10 sizes. out. print ("1. position, limit, and capacity:"); System. out. println ("position =" + buf. position () + ", limit =" + buf. limit () + ", capacty =" + buf. capacity (); int temp [] = {5, 7, 9}; // defines an int array buf. put (3); // set a data buf. put (temp); // four records are stored in the System. out. print ("2. position, limit, and capacity:"); System. out. println ("position =" + buf. position () + ", limit =" + buf. limit () + ", capacty =" + buf. capacity (); buf. flip (); // reset the buffer // postion = 0, limit = original position System. out. print ("3. position, limit, and capacity:"); System. out. println ("position =" + buf. position () + ", limit =" + buf. limit () + ", capacty =" + buf. capacity (); System. out. print ("buffer content:"); while (buf. hasRemaining () {int x = buf. get (); System. out. print (x + ",");}}}

If a buffer is created, the JVM can directly perform local I/O operations on it.

Import java. nio. byteBuffer; public class ByteBufferDemo {public static void main (String args []) {ByteBuffer buf = ByteBuffer. allocateDirect (10); // prepare 10 buffer bytes temp [] = {1, 3, 5, 7, 9}; // set the content buf. put (temp); // set a set of buf content. flip (); System. out. print ("content in the primary buffer:"); while (buf. hasRemaining () {int x = buf. get (); System. out. print (x + ",");}}}
Channel)

The non-blocking mode of Java NIO enables a thread to send requests from a channel to read data, but it can only obtain currently available data. If no data is available, you won't get anything. Instead of keeping the thread congested, the thread can continue to do other things until the data becomes readable. This is also true for non-blocking writes. A thread requests to write some data to a channel, but does not need to wait for it to write completely. This thread can also do other things. Threads usually use the idle time of non-blocking IO to execute IO operations on other channels, so a separate thread can now manage multiple input and output channels ).

The Java NIO channel is similar to a stream, but it is somewhat different:

  • Data can be read from the channel and written to the channel. However, stream read/write is usually unidirectional.
  • The channel can be read and written asynchronously.
  • The data in the channel always needs to read a Buffer first, or always needs to be written from a Buffer.

As mentioned above, data is read from the channel to the buffer zone, and data is written from the buffer zone to the channel.

Channel implementation

These are the most important channel implementations in Java NIO:

  • FileChannel
  • DatagramChannel
  • SocketChannel
  • ServerSocketChannel

FileChannel reads and writes data from a file.

Mongoramchannel can read and write data in the network through UDP.

SocketChannel can read and write data in the network through TCP.

The ServerSocketChannel can listen to new TCP connections, just like the Web server. A SocketChannel is created for each new connection.

Two-way input and output operations can be completed through the channel. There is also a way in the channel called memory ing.

Comparison of several reading methods

RandomAccessFile is slow. FileInputStream is slow. Buffer reading speed is fast.
The fastest memory ing speed
FileChannel memory ing instance
Import java. nio. byteBuffer; import java. nio. mappedByteBuffer; import java. nio. channels. fileChannel; import java. io. file; import java. io. fileOutputStream; import java. io. fileInputStream; public class FileChannelDemo03 {public static void main (String args []) throws Exception {File file File = new File ("d:" + File. separator + "oumyye.txt"); FileInputStream input = null; input = new FileInputStream (file); FileChannel fin = null; // define the input channel fin = input. getChannel (); // obtain the input channel MappedByteBuffer mbb = null; mbb = fin. map (FileChannel. mapMode. READ_ONLY, 0, file. length (); byte data [] = new byte [(int) file. length ()]; // The int foot = 0; while (mbb. hasRemaining () {data [foot ++] = mbb. get (); // read data} System. out. println (new String (data); // output content fin. close (); input. close ();}}

When operating the above Code, it may be very dangerous to execute the write operation, because simply changing a single element in the array is a simple operation, it is possible to directly modify the files on the disk, because the modification data is the same as the data stored on the disk.

 

Selector (Selectors )

Selector is a component that can detect one or more NIO channels in Java NIO and know whether the channel is prepared for read/write events. In this way, a single thread can manage multiple channels to manage multiple network connections.

Why use Selector?

The advantage of using a single thread to process multiple Channels is that fewer threads are needed to process Channels. In fact, you can use only one thread to process all the channels. For the operating system, context switching between threads is costly, and each thread occupies some system resources (such as memory ). Therefore, the fewer threads used, the better.

However, remember that the performance of modern operating systems and CPUs is getting better and better in terms of multitasking, so the overhead of multithreading becomes smaller and smaller over time. In fact, if a CPU has multiple kernels, the CPU capability may be wasted if no multi-task is used. In any case, the discussion about that design should be put in another article. Here, it is sufficient to know that Selector can process multiple channels.

Key Points

You can use Selector to build a non-blocking network service.

In the new I/O Implementation Network Program, the ServerSocketChannel class and SocketChannel are required.

Selector instance

The following describes how to use Selector to perform simple server operations. The server can listen on multiple ports at the same time. The main function of this server is to return the current time.

Import java.net. inetSocketAddress; import java.net. serverSocket; import java. util. set; import java. util. iterator; import java. util. date; import java. nio. channels. serverSocketChannel; import java. nio. byteBuffer; import java. nio. channels. socketChannel; import java. nio. channels. selector; import java. nio. channels. selectionKey; public class DateServer {public static void main (String args []) throws Excep Tion {int ports [] = {8000,8001, 8002,8003, 8005,8006}; // indicates five listening ports: Selector selector = Selector. open (); // select Selector for (int I = 0; I <ports. length; I ++) {ServerSocketChannel initSer = null; initSer = ServerSocketChannel. open (); // open the server channel initSer. configureBlocking (false); // server configuration is not blocked ServerSocket initSock = initSer. socket (); InetSocketAddress address = null; address = new InetSocket Address (ports [I]); // instantiate the binding Address initSock. bind (address); // bind the service to initSer. register (selector, SelectionKey. OP_ACCEPT); // wait for the System to be connected. out. println ("server running, listening on" + ports [I] + "port. ");} // Receives all generated keys, and checks whether to obtain the output int keysAdd = 0; while (keysAdd = selector. select ()> 0) {// select a group of keys, and the corresponding channel is ready to Set <SelectionKey> selectedKeys = selector. selectedKeys (); // retrieve all generated key Iterator <SelectionKey> iter = selectedKeys. iterator (); while (iter. hasNext () {SelectionKey key = iter. next (); // retrieve each key if (key. isAcceptable () {ServerSocketChannel server = (ServerSocketChannel) key. channel (); SocketChannel client = server. accept (); // receives a new client connection. configureBlocking (false); // The configuration is non-blocking. ByteBuffer outBuf = ByteBuffer. allocateDirect (1024); // outBuf. put ("current time:" + new Date ()). getBytes (); // set the content outBuf to the buffer. flip (); client. write (outBuf); // output content client. close (); // close} selectedKeys. clear (); // clear all keys }}}

After the server is complete, you can use the Telnet command to complete an operation server.

 

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.