Java Bio/nio

Source: Internet
Author: User

First, BIO

Blocking io (that is, blocking IO);

1. Features:

A) The socket server in the listening process of each accept to a client socket connection, it is necessary to deal with this request, and at this time other connected clients can only block wait;

b) Multithreading handles multiple connections, each of which has its own stack space and consumes some CPU time. Each thread will block out when it encounters an external unprepared. The result of blocking is a lot of thread context switching. And most of the thread context switches may be meaningless. For example, if a thread listens on a port, only a few requests come in a day, but the CPU has to do a context-switching attempt for that thread, and most of the switching ends up blocking.

2. Process:

Second, NIO

Java New io (i.e. non-blocking IO)

1. Features:

A) A dedicated thread handles all IO events and is responsible for distribution.

b) Event-driven mechanism: events are triggered at the time of the event, rather than synchronized to monitor events.

c) Thread communication: The threads communicate through wait,notify and other means. Ensure that each context switch is meaningful. Reduce the unnecessary process switching.

2. Example:

Server-side:

Serversocketchannel Serversocketchannel = Serversocketchannel.open ();

Serversocketchannel.socket (). bind (New Inetsocketaddress (9999));

while (true) {

Socketchannel Socketchannel = serversocketchannel.accept ();

Do something with Socketchannel ...

}

Client:

Socketchannel Socketchannel = Socketchannel.open ();

Socketchannel.connect (New Inetsocketaddress ("http://jenkov.com", 80));

Bytebuffer buf = Bytebuffer.allocate (48);

int bytesread = Socketchannel.read (BUF);

String NewData = "New String to write to file";

Bytebuffer buf = Bytebuffer.allocate (48);

Buf.clear ();

Buf.put (Newdata.getbytes ());

Buf.flip ();

while (Buf.hasremaining ()) {

Channel.write (BUF);

}

3. Channels (channel):

Important implementation classes:

1) FileChannel: Read and write data from the file.

2) Datagramchannel: can read and write data on the network through UDP.

3) Socketchannel: can read and write data in the network via TCP.

4) Serversocketchannel: You can listen for incoming TCP connections, like Web servers. A socketchannel is created for each new incoming connection.

Important methods:

Read (BUF): reads data from the channel into the BUF;

Write (BUF): Writes the data in the BUF to the channel;

Where Filechanel provides a map method that returns a Mappedbytebuffer object that represents the memory-mapped file IO, which can be much faster than regular stream-based or channel-based I/O. Memory-mapped file I/O is done by making the data in the file appear as the contents of a memory array.

4. Buffers (buffer):

Essentially a piece of memory that can write data and then read the data from it. Used to interact with the NIO channel (the data is read from the channel into the buffer, written from the buffer to the channel);

Inheritance Relationship:

Important attributes:

Serial number

Name

Properties feature

Description

1

Capacity

Buffer size

The total byte size of the buffer memory area;

2

Limit

Actual data size

In read mode, limit indicates how much data you can read, and in write mode, it indicates how much data you can write to buffer, and in write mode, limit equals buffer's capacity.

3

Position

Current position

Represents the current location. The initial position value is 0,position maximum can be capacity–1;

Important methods:

Serial number

Method name

Method functions

Description

1

Flip

Switch to read mode

A method that is called when switching from write mode to read mode, which indicates how much content can be read;

The specific implementation is: Set the position back to 0, and set the limit to the value of the previous position;

2

Rewind

Reread all the data in buffer;

Setting the position back to 0,limit remains the same, still indicating how much data can be read from buffer;

3

Clear

Compact

emptying buffers

The limit is used to empty the entire buffer, while the compact is used to copy the unread data to the front of the buffer and empty the rest when the buffer has partially unread data;

The limit and compact are all modified pointers when the buffer is cleared, allowing the data to be overwritten when the buffer is written, and not really emptying the contents of the buffer;

4

Mark

Reset

Mark

Recovery token

The mark () method marks a specific position in buffer. Restore the position by calling the reset () method;

5

Equals

CompareTo

Judging if they are equal

Compare size

equals equal condition:

1. Have the same type (byte, char, int, etc.).

The remaining number of Byte, char, and so on in 2.Buffer is equal.

All remaining byte, char, and so on in 3.Buffer are the same.

CompareTo: Determine the condition of buffer a less than buffer B:

1. The first unequal element is smaller than the corresponding element in the other buffer.

2. All elements are equal, but the first buffer is exhausted before the other (the number of elements in the first buffer is less than the other one).

Note: The remaining elements are from position to the Limit the elements between

6

Slice

Buffer shards

Creates a sub-buffer based on an existing buffer object, which is a single slice of the existing buffer as a new buffer, but the existing buffer is data-shared with the created sub-buffer at the underlying array level, that is, the child buffer is equivalent to a view window of the existing buffer

7

Asreadonlybuffer

To create a read-only buffer

This method returns a buffer that is exactly the same as the original buffer and shares the data with the original buffer, except that it is read-only. If the contents of the original buffer are changed, the contents of the read-only buffer change;

8

Allocatedirect

Direct buffers

Given a direct byte buffer, the Java Virtual machine will do its best to perform the native I/O operations directly against it. That is, it attempts to avoid copying the contents of the buffer into an intermediate buffer or copying data from an intermediate buffer every time before (or after) the native I/O operation of the underlying operating system is invoked.

5. Selectors (selector):

Selectors are used to listen for events on multiple channels (e.g., connection open, data arrival). Therefore, a single thread can listen on multiple data channels.

To use selector, you have to register the channel with selector and then call its select () method, then wait for the event to be ready and handle the event;

Usage:

1) when used with selector, the channel must be in non-blocking mode. This means that FileChannel cannot be used with selector because FileChannel cannot switch to nonblocking mode. Socket channels are available.

2) Selector Listener event set: Selectionkey.op_connect, Selectionkey.op_accept, Selectionkey.op_read, Selectionkey.op_write;

3) The method of separating the event from the Selectionkey:

int interestset = Selectionkey.interestops ();

Boolean isinterestedinaccept= (Interestset & selectionkey.op_accept) = = Selectionkey.op_accept;

Boolean isinterestedinconnect = (Interestset & selectionkey.op_connect) = = Selectionkey.op_connect;

Boolean isinterestedinread = (Interestset & selectionkey.op_read) = = Selectionkey.op_read;

Boolean isinterestedinwrite = (Interestset & selectionkey.op_write) = = Selectionkey.op_write;

The above method is also encapsulated in the same selectionkey:

Selectionkey.isacceptable ();

Selectionkey.isconnectable ();

Selectionkey.isreadable ();

Selectionkey.iswritable ();

Use process:

Java Bio/nio

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.