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 is NIO in Java

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

Share

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

This article mainly introduces "what is NIO in Java". In daily operation, I believe many people have doubts about what is NIO in Java. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful for you to answer the doubt of "what is NIO in Java?" Next, please follow the editor to study!

What is NIO?

   NIO, or NEW Imax O, is a new set of Imax O standards introduced in JDK1.4. NIO is based on Block and uses blocks as the basic unit to process data. And Buffer support is provided for all basic types.    data is read from Channel to Buffer, or written from Buffer to Channel. Selector listens for multiple Channel events, such as opening a link or data arrival.

Graph LR A ((Channel))-- read-- > B [buffer] graph LR A [Buffer]-- write-- > B ((Channel)) compare the difference of traditional Imax O

1. The traditional Imax O is based on byte stream and character stream, while NIO is based on Channel and Buffer for data operation. 2. IO is stream-oriented and NIO is Buffer buffer-oriented. Stream-oriented means that read data reads bytes from the stream one by one until all bytes are read. If you need to move the read data back and forth, you need to establish a buffer. The Buffer of NIO does just this, and the data can be easily manipulated after the data is read from Channel to the buffer. 3. The IO operation is a blocking mode. When the read () or write () operation is called, the thread blocks until all the data is read or written. NIO is a non-blocking mode. When reading data from Channel, if there is no data available, it gets nothing and does not block threads from waiting. Instead, it spends its free time performing IO operations on other Channel, so a single thread can manage multiple Channel.

Three core parts of NIO

Channel (channel) Buffer (buffer) Selector (selection area)

Channel

Referred to as "channel" or "channel", it is the same level as the Stream in the IO stream, but the Stream is unidirectional and the Channel is bidirectional, so it can be used for both read and write operations. The main implementation is:

FileChannel

DatagramChannel

SocketChannel

ServerSocketChannel

FileChannel

Example: traditional IO

/ * * traditional IO operations read files * / public static void oldIo () {InputStream inputStream = null; try {inputStream = new BufferedInputStream ("src\\ main\\ java\\ top\\ qrainly\\ demo\\ nio\ OldIO.txt"); byte [] bytes = new byte [1024]; int read = inputStream.read (bytes) System.out.println (read); while (readreadable colors 1) {for (int iTunes 0 political I 0) {buffer.flip (); while (buffer.hasRemaining ()) {System.out.println ((char) buffer.get ());} buffer.clear (); bytesRead = socketChannel.read (buffer) } if (bytesRead = =-1) {socketChannel.close ();}} / * deal with writing * @ param key * @ throws IOException * / public static void handleWrite (SelectionKey key) throws IOException {ByteBuffer buffer = (ByteBuffer) key.attachment (); buffer.flip (); SocketChannel socketChannel = (SocketChannel) key.channel () While (buffer.hasRemaining ()) {socketChannel.write (buffer);} buffer.compact ();}

The    Selector class can be used to avoid the need to read and distribute using resource-wasting "busy" methods in blocking clients. This requires a way to block the wait until at least one channel is available for Icano operation and indicates which channel it is. The selector of NIO implements this function. A Selector instance can simultaneously check the Imax O status of a set of channels. In technical terms, a selector is a multiplex switch selector because a selector can manage Ibank O operations on multiple channels. However, if you deal with so many clients in the traditional way, the method used is to check whether all clients have IUnip O operations one by one. If the current client has IUnip O operations, the current client may be thrown to a thread pool for processing. If there is no Igamo operation, the next poll will be carried out. When all clients have been polled, they will then start polling from scratch. This method is very stupid and a waste of resources, because most clients do not have an Icano operation, and we also have to check it; but Selector is different, it can manage multiple Icano internally, when a channel has an Icano operation, he will inform Selector,Selector to remember that the channel has an Icano operation, and know which Icando operation is read? Is it to write? Still accept the new connection;    uses Selector, and it returns only two results, one is 0, that is, no client needs to operate IUnip O at the time of your call, and the other result is a group of clients that need to operate IUnip O, then you don't need to check it at all, because it definitely returns you what you want. Such a notification method is much more efficient than that kind of active polling!

When    is used with Selector, Channel must be in non-blocking mode. This means that FileChannel cannot be used with Selector because FileChannel cannot switch to non-blocking mode. And socket channels are fine.

Selector

   asynchronous network IO Selector runs a single thread to deal with multiple Channel. If the application opens multiple channels and the traffic of a single connection is very low, it is very convenient to use Selector. Register Channel with Selector, and then use the select () method, which blocks until the registered channel is ready for events, such as connection opening or data arrival. To use a selector (Selector) for   , you need to create an instance of Selector (using the static factory method open ()) and register it to the channel you want to monitor (note that this is done through the method of channel, not the method of selector). Finally, the select () method of the selector is called. This method blocks the wait until one or more channels are ready for the Icord O operation or wait for a timeout. The select () method returns the number of channels that can be operated by Icano. Now, in a single thread, it is possible to check whether multiple channels are ready for the Ihand O operation by calling the select () method. If the channel is still not ready after a period of time, the select () method returns 0 and allows the program to continue with other tasks.

Buffer

There are four important parameters in Buffer: location (position), capacity (capactiy), upper limit (limit), and tag (mark)

Parameter write mode location (position) the location of the current buffer, starting from the next location of the position, the location of the current buffer read, and the upper limit of the total capacity of the next location capacity (capactiy) buffer of the position. The upper limit of the total capacity of the buffer (limit) buffer Limit0# deposit-> deposit # # Save-> save-> save ten bytes of data to complete # limit=15 capacity=15 position=10# call flip () Method # after calling the flip () method # limit=10 capacity=15 position=0# starts reading five bytes of data # "read byte data-- > 0" read byte data-- > 1 "2" data # # read byte data-- > 2 read byte data-- > 3 read byte data-- > "read five bytes of data complete # limit=10 capacity=15 position=5# call flip () method # # # three important methods of # limit=5 capacity=15 position=0 after calling the flip () method

1. Rewind ()-sets position to zero and clears the flag bit (mark 2, clear ()-sets position to zero, while setting limit to the size of capacity, and clears the flags mark 3, flip ()-first sets limit to position, then sets position to zero, and clears the flag bit mark-usually used for read-write conversion

File mapping to memory

Example:

/ * File mapped to memory * / public static void mapperMemory () {RandomAccessFile randomAccessFile = null; try {randomAccessFile = new RandomAccessFile ("src\\ main\\ java\\ top\\ qrainly\\ demo\\ nio\\ NIO.txt", "rw"); FileChannel fileChannel = randomAccessFile.getChannel () / / Map the file to memory MappedByteBuffer mappedByteBuffer = fileChannel.map (FileChannel.MapMode.READ_WRITE, 0 recording AccessFile.length ()); while (mappedByteBuffer.hasRemaining ()) {System.out.println ((char) mappedByteBuffer.get ()) } / / modify the file mappedByteBuffer.put (0, (byte) 98);} catch (IOException e) {e.printStackTrace ();} finally {try {if (randomAccessFile! = null) {randomAccessFile.close () }} catch (IOException e) {e.printStackTrace ();} at this point, the study of "what is NIO in Java" is over, hoping to solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

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