Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the knowledge points of Java NIO?

2025-03-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article introduces the relevant knowledge of "what are the knowledge points of Java NIO". In the operation of actual cases, many people will encounter such a dilemma. Next, let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

I. several basic concepts in NIO

There are several key concepts in NIO: Channel (channel), Buffer (buffer), and Selector (selector).

First of all, let's start with Channel. Channel, as its name implies, is the way to something, providing a channel for someone. In traditional IO, we read the contents of a file, usually like this:

Public class Test {public static void main (String [] args) throws IOException {File file = new File ("data.txt"); InputStream inputStream = new FileInputStream (file); byte [] bytes = new byte [1024]; inputStream.read (bytes); inputStream.close ();}}

The InputStream here actually provides a channel for reading files.

So you can compare Channel in NIO with Stream in traditional IO, but note that in traditional IO, Stream is one-way, for example, InputStream can only read and OutputStream can only write. Channel is bi-directional and can be used for both read and write operations.

Buffer (buffer) is a very important thing in NIO. In NIO, all data can not be read and written without Buffer. For example, in the above code, the read data is placed in the byte array, while in NIO, the read data can only be placed in the Buffer. Similarly, the data is written to the Buffer first.

Let's take a look at one of the core things in NIO: Selector. It can be said that it is the most critical part of NIO. The role of Selector is to poll each registered Channel. Once it is found that a registered event has occurred in Channel, it will get the event and deal with it.

For example, look at the following example:

Use a single thread to process a Selector, and then get the arrival events through the Selector.select () method, and after getting the arrival events, you can respond to these events one by one.

II. Channel

As mentioned earlier, Channel is very similar to Stream in traditional IO. Although it is very similar, there are great differences. The main difference is that the channel is bi-directional and can be read or written through a Channel, while Stream can only operate in one direction and can only read or write through a Stream.

Here are some common channels:

FileChannel

SocketChanel

ServerSocketChannel

DatagramChannel

The data can be read from or written to the file by using FileChannel; the data can be read and written to both ends of the network connection by TCP through SocketChannel; the TCP connection initiated by the client can be monitored through ServerSocketChanel and a new SocketChannel is created for each TCP connection to read and write data; through DatagramChannel, the data is read and written to both ends of the network connection with UDP protocol.

Here is an example of writing data to a file through FileChannel:

Public class Test {public static void main (String [] args) throws IOException {File file = new File ("data.txt"); FileOutputStream outputStream = new FileOutputStream (file); FileChannel channel = outputStream.getChannel (); ByteBuffer buffer = ByteBuffer.allocate (1024); String string = "java nio"; buffer.put (string.getBytes ()); buffer.flip () / / buffer's flip method channel.write (buffer); channel.close (); outputStream.close ();}} must be called here

Through the above program, the string "java nio" will be written to the data.txt file under the project directory. Note that the flip method of buffer must be called before calling the write method of channel, otherwise the content cannot be written correctly. The specific reasons will be explained in the next blog article when describing the usage of Buffer.

III. Buffer

Buffer, hence its name, buffer, is actually a container, a contiguous array. Channel provides a channel to read data from files and networks, but all data read or written must go through Buffer. You can understand it by looking at the following picture:

The figure above depicts the process of sending data from a client to the server, and then receiving the data from the server. When the client sends data, it must first store the data in the Buffer, and then write the contents of the Buffer to the channel. The data received by the server side must be read into the Buffer through Channel, and then extracted from the Buffer for processing.

In NIO, Buffer is a top-level parent class, it is an abstract class, and the common subclasses of Buffer are:

ByteBuffer

IntBuffer

CharBuffer

LongBuffer

DoubleBuffer

FloatBuffer

ShortBuffer

If it is for file reading and writing, the above Buffer may be used. But for network reading and writing, ByteBuffer is the most commonly used.

The specific use of Buffer and the understanding of its limit, posiion, and capacity attributes will be covered in the next article.

IV. Selector

The Selector class is the core class of NIO. Selector can detect whether there are events on multiple registered channels, and if there are events, get the events and deal with the corresponding response to each event. In this way, multiple channels can be managed with a single thread, that is, multiple connections. In this way, only when there are real read and write events in the connection, the function will be called to read and write, which greatly reduces the system overhead, and does not have to create a thread for each connection, does not have to maintain multiple threads, and avoids the overhead caused by context switching between multiple threads.

A key class related to Selector is SelectionKey, where a SelectionKey represents an arriving event, and these two classes constitute the key logic for the server to handle the business.

This is the end of the content of "what are the knowledge points of Java NIO". Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report