Java NIO Summary

Source: Internet
Author: User

First, NIO

NIO is new IO and is also non-blocking IO. There are channel, Selector, Buffer, Pipe, Filelock and other classes.

Buffer in Java.nio Package

Channel, Selector, Pipe, filelock etc. in Java.nio.channels bag

Ii. Channels of Channel

Set non-blocking configureblocking (false);

Register Selector Register (SELECTOR,SELECTIONKEY.OP_XXX)

How to use Read (buffer), write (buffer)

Use method Open () to get channel

    • FileChannel using Fileinputstream,fileoutputstream,randomaccessfile or open (path path, openoption ... options) Can get channel object
    • Serversocketchannel
    • Socketchannel
    • Datagramchannel
    • Pipe.sinkchannel using Pipe.sink ()
    • Pipe.sourcechannel using Pipe.source ()

Third, buffer buffering

In addition to the Boolean type without the buffer class, there are buffer buffers for the other seven basic data types. and byte has two buffer buffers, one in the heap, and one in the memory map area of the file.

Method Clear () empty buffer

Method Compact () moves the buffer data to the starting position, set to position at the end of the data

Method Flip () reverses buffer to turn the write mode into read mode

Method Rewind () reads data starting from 0

Method Hasremaining () to determine if there is any remaining data

Bytebuffer

Shortbuffer

Intbuffer

Longbuffer

Floatbuffer

DoubleBuffer

Charbuffer

Mappedbytebuffer throughFileChannel.map方法产生

Iv. Selector Selector
Selector Selector = selector.open (); Channel.configureblocking (false= Channel.register ( Selector,selectionkey.op_read);

Select method

int Select () int Select (long  timeout)int selectnow ()

select()Blocking to at least one channel is ready for your registered event.

select(long timeout)As with select (), except for the longest block of timeout milliseconds (parameters).

selectNow()will not block, no matter what channel is ready to return immediately

Call the Selector.wakeup () method and block the line routines on the Select () method to return immediately.

Calling its close () method after the selector is exhausted closes the selector and invalidates all Selectionkey instances registered on the selector. The channel itself is not closed.

Wu, Selectionkey

Selector Four events are represented by four constants of the Selectionkey:

Selectionkey.op_connect

Selectionkey.op_accept

Selectionkey.op_read

Selectionkey.op_write

The Select method in selector returns not 0 o'clock, gets selectionkey

Set<selectionkey> Selectedkeys =Selector.selectedkeys (); Iterator Keyiterator=selectedkeys.iterator (); while(Keyiterator.hasnext ()) {
Selectionkey Key
=Keyiterator.next (); if(Key.isacceptable ()) {//a connection is accepted by a serversocketchannel. } Else if(Key.isconnectable ()) {//A connection is established with a remote server. } Else if(Key.isreadable ()) {//A channel is ready for reading } Else if(Key.iswritable ()) {//A channel is ready for writing} keyiterator.remove (); //must be removed, or the next channel will remain in the Selectionkeyset. }

Vi. pipe pipes (1) sinkchannel
Pipe pipe= = = "A sink pipe channel"= bytebuffer.allocate (buf.clear); Buf.put ( Data.getbytes ()); Buf.flip ();  while (Buf.hasremaining ()) {    sinkchannel.write (BUF);}

(2) Sourcechannel
Pipe.sourcechannel Sourcechannel == bytebuffer.allocate (a); int length = Sourcechannel.read (BUF);

Seven, Filelock

Filelock is similar to the lock interface but does not implement the lock interface

(1) Concept

    • Shared Lock: Shared read operation, but only one write (read can at the same time, but write not)
    • Exclusive lock: Only one read or one write (neither read nor write at the same time)

(2) Filelock Filechannel.lock (long position, long size, Boolean shared)

Shared meaning: Whether to use share locks, some operating systems that do not support shared locks, will automatically change the shared lock to exclusive lock. You can detect what type of lock is obtained by calling the IsShared () method.

(3) The difference between lock () and Trylock ():

Lock () Blocking method, the locking range can increase as the file grows. The default lock () is exclusive, and the lock is shared (0L, Long.max_value, True).

Trylock () non-blocking, returns NULL when no lock is obtained.

(4) Filelock life cycle: In Call Filelock.release (), or channel.close (), or the JVM shuts down

(5) Filelock is thread-safe

(6) within the same process, it cannot be acquired again until the file lock is not released. That is, before the release () method call, only lock () or Trylock () can be used once.

FileChannel channel =NULL; Filelock Lock=NULL; Try{Randomaccessfile RAF=NewRandomaccessfile ("Data.txt", "RW"); Channel=Raf.getchannel (); //Get Lock Method One: Lock (), blocking method, when the file lock is not available, the current process will be suspendedLock = Channel.lock ();//no parameter lock () is an exclusive lock//lock = Channel.lock (0L, Long.max_value, true);//there is a shared lock, a write operation will report an exception//get the Lock method two: Trylock (), non-blocking method, when the file lock is not available, Trylock () will get a null value//Do {//lock = Channel.trylock (); //} while (null = = Lock); }Catch(Exception e) {}finally{            if(lock!=NULL) {lock.release (); }            if(channel!=NULL) {channel.close (); }        }

Eight, Serversocketchannel server channel
 Packagecn.edu.scau.mk;Importjava.io.IOException;Importjava.net.InetSocketAddress;ImportJava.nio.channels.ServerSocketChannel;ImportJava.nio.channels.SocketChannel;/** * * @authorMK*/ Public classTest {volatile Static Booleanisfinished =false;  Public Static voidMain (string[] args)throwsIOException {serversocketchannel Serversocketchannel=Serversocketchannel.open (); Serversocketchannel.socket (). Bind (NewInetsocketaddress (888));  while(!isfinished) {Socketchannel Socketchannel=serversocketchannel.accept (); //1. Blocking mode//thread handling Socketchannel ...//2. Non-blocking mode            if(Socketchannel! =NULL) {                //Handling Socketchannel ...}} serversocketchannel.close (); }}

Nine, Socketchannel TCP channel
 Packagecn.edu.scau.mk;Importjava.io.IOException;Importjava.net.InetSocketAddress;ImportJava.nio.ByteBuffer;ImportJava.nio.channels.SocketChannel;/** * * @authorMK*/ Public classTest {volatile Static Booleanisfinished =false;  Public Static voidMain (string[] args)throwsIOException {socketchannel Socketchannel=Socketchannel.open (); Socketchannel.configureblocking (false);//set to non-blockingSocketchannel.connect (NewInetsocketaddress ("https://www.baidu.com", 80)); String Data= "A socket Channel connect"; Bytebuffer buf= Bytebuffer.allocate (48);        Buf.clear ();        Buf.put (Data.getbytes ());        Buf.flip ();  while(!Socketchannel.finishconnect ()) {            //wait for the connection to succeed or to do something else        }        //the non-blocking state is likely to return without writing data.         while(Buf.hasremaining ()) {socketchannel.write (BUF);    } socketchannel.close (); }}

Ten, Datagramchannel UDP channel
 Packagecn.edu.scau.mk;Importjava.io.IOException;Importjava.net.InetSocketAddress;Importjava.net.SocketAddress;ImportJava.nio.ByteBuffer;ImportJava.nio.channels.DatagramChannel;ImportJava.nio.channels.SocketChannel;/** * * @authorMK*/ Public classTest {volatile Static Booleanisfinished =false;  Public Static voidMain (string[] args)throwsIOException {Datagramchannel channel=Datagramchannel.open (); Channel.socket (). Bind (NewInetsocketaddress (888)); //Channel.connect (New inetsocketaddress ("www.baidu.com");Bytebuffer buf = Bytebuffer.allocate (48);        Buf.clear (); //ReceiveSocketAddress sa=channel.receive (BUF); //The connect channel can use the Read//int bytesread = Channel.read (BUF);buf.clear (); Buf.put ("Datagram Channel". GetBytes ());        Buf.flip (); //Send        intLength = Channel.send (buf,NewInetsocketaddress ("www.baidu.com", 80)); //The connect channel can use the write//Channel.write (BUF);Channel.close (); }}

Java NIO Summary

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.