In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces "what are the basic operations of NIO". In the daily operation, I believe that many people have doubts about the basic operation of NIO. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts about "what are the basic operations of NIO?" Next, please follow the editor to study!
NIO
Synchronous non-blocking
The difference between blocking and non-blocking:
When blocking, when the result of the call returns, the current thread is suspended and returns after the result is obtained
In the case of non-blocking, if the result cannot be obtained immediately, the call will not block the current thread, and the caller needs to poll regularly to check the processing status.
Channel (channel) and Buffer (buffer)
The difference and relationship with ordinary IO
NIO processes data in blocks, but IO writes and reads in the form of the most basic byte stream
NIO no longer processes data in the form of OutputStream and InputStream input streams as IO does, but it uses channels and buffers to process data based on this stream.
The channel of NIO can be bi-directional, and the flow of IO can only be unidirectional.
NIO buffers (byte array) can also be sliced, and read-only buffers, direct buffers and indirect buffers can be established. Read-only buffers are read-only buffers, and direct buffers are buffers that allocate memory in a special way to speed up the speed of NIO.
NIO uses the multiplexed IO model, and BIO uses the blocking IO model.
The concept of channel
The channel is a simulation of the flow in the original Istroke O packet. All data to any destination must go through a Channel object (channel). A Buffer is essentially a container object. All objects sent to a channel must first be placed in the buffer; any data read from the channel must be read into the buffer
The concept of buffer
A Buffer is an object that contains data to be written to or just read out. Add a Buffer object to NIO, and in streaming IO, write or read data directly to the Stream object
In the NIO library, all data is processed with buffers. When reading data, it reads directly into the buffer. When writing data, it is written to the buffer. Whenever you access data in NIO, you need to put it in a buffer
The buffer is essentially an array. It is usually a byte array, but other kinds of arrays can also be used. But a buffer is not only an array, it provides structured access to data, but also tracks the read / write process of the system.
ByteBufferCharBufferShortBufferIntBufferLongBufferFloatBufferDoubleBuffer selector
Selector is a multiplexer that detects events from multiple channels at the same time to achieve asynchronous Imax O.
Multiple socket channels are monitored simultaneously by a selector, and when the socket channel has an available event, the channel is changed to an available state, and the selector can achieve the available state.
working principle
Client-"Channel-" Selector- "keys-- status change -" server
Buffer buffer Channel channel Selector selector
Server side creates ServerSocketChannel with a Selector multiplexer polling all registered channels and performing relevant operations according to channel status
Connect connection status
Accept blocking state
Read readable statu
Write writable state
The Client side creates a Selector that the SocketChannel registers with the Server side
Buffer
The total length of the capacity buffer array
The location of the next data element to be manipulated by position
The location of the next inoperable element in the limit buffer array, and the limit operation ByteBuffer is used for reading and writing, and exclusively accesses and locks the file region / / writes the file try (FileChannel fileChannel = new FileOutputStream (FILE). GetChannel ()) {fileChannel.write ("test" .getBytes ());} catch (IOException e) {throw new RuntimeException ("write file failed", e) } / / write try at the end of the file (FileChannel fileChannel = new RandomAccessFile (FILE, "rw"). GetChannel () {fileChannel.position (fileChannel.size ()); / / move to the end of the file fileChannel.write (ByteBuffer.wrap ("some" .getBytes ());} catch (IOException e) {throw new RuntimeException ("write end failed", e) } try (FileChannel fileChannel = new FileInputStream (FILE). GetChannel (); FileChannel out = new FileOutputStream ("C:\\ Users\\ sinosoft\\ Desktop\\ copy.txt"). GetChannel () {/ / read operation, need to call allocate display assignment ByteBuffer ByteBuffer byteBuffer = ByteBuffer.allocate (1024) / / after read, put the data into the buffer while (fileChannel.read (byteBuffer)! =-1) {byteBuffer.flip (); / / prepare to write out.write (byteBuffer); byteBuffer.clear () / / clear cache}} catch (IOException e) {throw new RuntimeException ("failed to read file", e);}} method description
The rewind () method sets position to the start of the buffer
Both get () and put () modify position
Neither get (int) nor put (int) modifies position
Mark () sets mark to the current position
Flip () switches write mode to read mode
Public final Buffer flip () {limit = position; position = 0; mark =-1; return this;} memory mapping file
Memory-mapped files can create and modify files that are too large to fit into memory.
RandomAccessFile tdat = new RandomAccessFile ("test.dat", "rw"); MappedByteBuffer out = tdat.getChannel (). Map (FileChannel.MapMode.READ_WRITE, 0, length); or FileChannel fc = new FileInputStream (new File ("temp.tmp"). GetChannel (); IntBuffer ib = fc.map (FileChannel.MapMode.READ_ONLY,0, fc.size ()). AsIntBuffer ()
Mapping file access has much higher performance than standard IO
File locking
File locks can be accessed synchronously, and file locks are visible to other operating system processes because java file locks map directly to native operating system locking tools.
Public class FileLockTest {private static final String FILE = "C:\ Users\\ sinosoft\\ Desktop\\ remaining working copy .txt"; public static void main (String [] args) throws IOException, InterruptedException {FileChannel fileChannel = new FileOutputStream (FILE). GetChannel (); / / file lock FileLock fileLock = fileChannel.tryLock () Thread thread = new Thread (new Runnable () {@ Override public void run () {FileChannel fileChannel = null; try {fileChannel = new FileOutputStream (FILE). GetChannel ();} catch (FileNotFoundException e) {e.printStackTrace () } ByteBuffer byteBuffer = ByteBuffer.allocate (1024); byteBuffer.put ("aqws" .getBytes ()); try {System.out.println ("Thread ready to write"); fileChannel.write (byteBuffer); System.out.println ("Thread finished") } catch (IOException e) {e.printStackTrace ();}); thread.start (); if (fileLock! = null) {ByteBuffer byteBuffer = ByteBuffer.allocate (1024); byteBuffer.put ("aqwqdqdhwfwihfejfhi" .getBytes ()) System.out.println ("main thread sleep"); Thread.sleep (10000); / / error java.nio.channels.NonWritableChannelException// fileChannel.read (byteBuffer); System.out.println ("main thread ready to write"); fileChannel.write (byteBuffer); fileLock.release () The main thread sleeps and prepares to write java.io.IOException: another program has locked part of the file and the process cannot access it. At sun.nio.ch.FileDispatcherImpl.write0 (Native Method) at sun.nio.ch.FileDispatcherImpl.write (FileDispatcherImpl.java:75) at sun.nio.ch.IOUtil.writeFromNativeBuffer (IOUtil.java:93) at sun.nio.ch.IOUtil.write (IOUtil.java:65) at sun.nio.ch.FileChannelImpl.write (FileChannelImpl.java:211) at com.zhanghe.study.io.nio.FileLockTest$1.run (FileLockTest.java 35) the at java.lang.Thread.run (Thread.java:745) main thread is ready to write
You can get the FileLock of the entire file by calling tryLock or lock on FileChannel (SocketChannel, DatagramChannel, and ServerSocketChannel do not need to be locked because they are essentially single-threaded entities)
TryLock () is non-blocking and attempts to acquire the lock. If it cannot, it simply returns from the method call.
Lock () blocks until the lock is acquired, or the thread calling lock () is interrupted, or the channel calling the lock () method is closed.
Use FileLock.release () to release the lock
/ / Lock part of the file and lock the size-position area. The third parameter specifies whether to share the lock tryLock (long position, long size, boolean shared). This ends the study of "what are the basic operations of NIO?". I hope to be able to solve your 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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.