NiO and Aio in Java

Source: Internet
Author: User
Tags new set

1. What is NiO

NIO is the abbreviation for new I/O, as opposed to the old stream-based I/O method, which, by name, represents a new set of Java I/O standards. It is included in the JDK in Java 1.4 and has the following characteristics:

    • NIO is block-based, which processes data in blocks as a basic unit (the units stored on the hard disk are also stored by block, which is better performance than a stream-based approach)

    • Provide (buffer) cache support for all primitive types

    • Increase the channel object as the new raw I/O abstraction

    • Support Locks (we often see some. lock files when we use them, which means that the thread is using the lock, and when the threads release the lock, the file is deleted so that other threads can continue to get the lock) and the file access interface of the memory-mapped file

    • Provides selector-based asynchronous network I/O

All the read and write operations from the channel pass through buffer, and the channel is the abstraction of Io, and the other end of the channel is the manipulated file.

2. Buffer

The implementation of buffer in Java. The basic data type has its corresponding buffer

Example of a simple use of buffer:

 public  class   Test { public  static  void  main (string[] args) throws   Exception {fileinputstream fin  = new FileInputStream (new   File ( "d:\\        Buffer.tmp " = Fin.getchannel ();        Bytebuffer Bytebuffer  = bytebuffer.allocate (1024);        Fc.read (Bytebuffer);        Fc.close (); Bytebuffer.flip ();  //  read-write conversion   

The steps used in the summary are:

1. Get Channel

2. Apply for buffer

3. Establishing a read/write relationship between channel and buffer

4. Close

The following example uses NIO to copy a file:

 Public Static voidNiocopyfile (string resource, string destination)throwsIOException {fileinputstream fis=NewFileInputStream (Resource); FileOutputStream Fos=NewFileOutputStream (destination); FileChannel Readchannel= Fis.getchannel ();//Read File ChannelFileChannel Writechannel = Fos.getchannel ();//Write file ChannelBytebuffer buffer = bytebuffer.allocate (1024);//read in data cache         while(true) {buffer.clear (); intLen =readchannel.read (buffer);//read in Data            if(len = =-1) {                 Break;//Read Complete} Buffer.flip (); writechannel.write (buffer);             //Write File} readchannel.close ();    Writechannel.close (); }

There are 3 important parameters in buffer: position (position), Capacity (capactiy), and upper limit (limit)

Here to distinguish between the capacity and the upper limit, such as a buffer 10KB, then 10KB is the capacity, I will 5KB of files read into buffer, then the upper limit is 5KB.

Most of the methods in buffer are to change these 3 parameters to achieve certain functions:

Public final Buffer Rewind () resets position to zero and clears the flag bit (mark)

Public final Buffer Clear () resets the position to zero, sets the limit to the size of capacity, and clears the flag mark

Public final Buffer Flip () sets the limit to the location of the position, then zeros the position and clears the flag mark, which is typically used when reading and writing conversions

File mapping to Memory

 Public Static voidMain (string[] args)throwsException {randomaccessfile RAF=NewRandomaccessfile ("C:\\mapfile.txt", "RW"); FileChannel FC=Raf.getchannel (); //mapping files to memoryMappedbytebuffer MBB = Fc.map (FileChannel.MapMode.READ_WRITE, 0, Raf.length ());  while(Mbb.hasremaining ()) {System.out.print (Char) Mbb.get ()); } mbb.put (0, (byte) 98);//Modify a fileRaf.close (); }

3. Channel

The channel is a bit like a stream, and a channel can correspond to a file or a network socket.

Selector is a selector that can select a channel and do something about it.

A thread can correspond to a selector, and a selector can poll multiple channel, and each channel corresponds to a socket.

When selector invokes select (), it checks to see if the client has the data ready. Select () blocks when no data is ready.

The difference between Selectnow () and select () is that Selectnow () is not blocked, and selectnow () does not block when no client is ready for the data, and will return 0 when the client has ready the data, Selectnow () Returns the number of prepared clients. NiO is usually said to be non-blocking, but there is a blockage if no data is prepared.

When the data is ready, after a call to select (), a selectionkey,selectionkey indicates that the data for a channel on a selector is ready.

This channel will only be selected if the data is ready.

This enables NIO to implement a thread to monitor multiple clients.

Differences and summaries of NIO and AIO

Nio:

1. When NiO prepares the data for processing by the application, the read/write process of the data is still done in the application thread , just splitting the waiting time into a separate thread.

2. Save data preparation time (because selector can be reused)

Aio:

1. notify me when you're done (kernel memory copy to working memory to process)

2. Do not speed up Io, just after reading the notification

3. Use callback functions for business processing

NIO is synchronous and non-blocking

AIO is asynchronous, non-blocking

Because NiO's reading and writing process is still done in the application thread, NIO is not suitable for long periods of read and write processes.

While the AIO read and write process is completed before being notified, AIO is capable of those heavy-duty, read and write process long tasks.

NiO and Aio in Java

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.