The abstract representation of the file, the byte stream and the file operation of the character stream are related to the traditional IO, and we have learned more deeply in the previous article.
However, the traditional IO stream still has a lot of flaws, especially its blocking and disk read and write is slow, which will lead to a significant reduction in CPU usage efficiency.
So, JDK 1.4 released the NIO package, NiO's file read and write design to subvert the traditional IO design, the use of "channel" + "buffer" so that the new IO operation directly toward the buffer, and non-blocking, for the efficiency of the upgrade is not a little bit two, we look at it together.
Channel channels
We have said that the core of NIO is the channel and the buffer, so their working mode is this:
The channel is a bit like the stream in IO, but the difference is that the same channel allows both read and write, and any stream is either a read stream or a write stream.
But you have to understand that the channel and the flow are all based on the physical file, and each stream or channel through the file pointer operation file, here said "channel is bidirectional" also has the premise, that is the channel based on random Access file "Randomaccessfile" readable writable file pointer.
"Randomaccessfile" is both readable and writable, so the channel based on it is bidirectional, so, "channel is two-way" this sentence is a prerequisite, can not be taken out of context.
The basic channel types are as follows:
- FileChannel
- Datagramchannel
- Socketchannel
- Serversocketchannel
FileChannel is a file-based channel, Socketchannel and Serversocketchannel used for network TCP sockets are reported to be read-write, Datagramchannel is used for network UDP socket Word read and write.
The channel cannot exist alone, it will always need to bind a buffer, all the data will only exist in the buffer, whether you write or read, it must be the buffer through the channel to reach the disk file, or disk files through the channel to reach the buffer.
That is, the buffer is the "starting point" of the data, but also the "end", specifically these channels exactly what is different and how to use, the basic implementation, we introduced the "buffer" concept, then do detailed study.
Buffer buffer
Buffer is the base class for all specific buffers and is an abstract class that has many implementation classes that contain caches of various types of data.
- Bytebuffer
- Charbuffer
- Shortbuffer
- Intbuffer
- Longbuffer
- Floatbuffer
- DoubleBuffer
- Mappedbytebuffer
We take Bytebuffer as an example to learn, the rest of the buffers are based on byte buffers, but only a step byte conversion process, Mappedbytebuffer is a special caching method, we will be introduced separately.
There are several important member properties in Buffer, which we'll look at:
private int mark = -1;private int position = 0;private int limit;private int capacity;long address;
Mark attributes we are no longer familiar with, for repeated reading. Capacity describes the buffer capacity, which is the maximum amount of data that can be stored in the entire buffer. Address is used to manipulate direct memory, which differs from JVM memory, which is explained later.
and position and limit I would like to use a picture to explain:
Because the buffers are read-write coexistence, the values of the two variables also have different meanings in different modes.
Write mode, the so-called write mode is to write the contents of the buffer into the channel. Position represents the position of the byte in the buffer where the next byte should be written, and the limit indicates the position of the last byte to be written in the buffer.
Read mode, the so-called read mode is to read data from the channel to the buffer . Position represents the next read byte should be stored in the buffer location, limit equals capacity.
Related to read and write operation details, will be together with you to see the source code, in order to deepen the channel and buffer cooperation work principle, here we first discuss a people may not how to pay attention to a problem.
JVM memory is divided into stacks and heaps, this is the knowledge of the mind, but in fact, the JVM is divided into a heap of external memory, that is, direct memory, many people do not know what this memory is for.
This is a piece of physical memory dedicated to the JVM and IO devices, and the Java bottom uses the C-language API to invoke the operating system to interact with the IO device.
For example, there is a byte array in Java memory, and now the call stream writes it to the disk file, the JVM first copies the byte array to the out-of-heap memory, and then invokes the C language API to indicate that data from a contiguous address range is written to disk.
Reads are similar, and the extra copy work of the JVM makes sense, because the JVM is run based on an automatic garbage collection mechanism, and all in-memory data is moved in the GC, if you call the system API to tell the operating system to write memory of a location of memory to disk, and a GC This part of the data is moved, and the operating system writes the wrong data after the GC is over.
So, in the case of the JVM interacting with the peripheral IO device, the memory data is copied to the out-of-heap memory, and then the system API is called to write to the disk indirectly, and the read is similar. Because the out-of-heap memory is not managed by GC, you must remember to release it after use.
Understanding this small knowledge is to understand the premise of the implementation of the source code, or you may not know what the implementation of the source is doing. Well, let's take a look at the basic use of read operations and the implementation of the source code.
RandomAccessFile file = new RandomAccessFile ("C:\\Users\\yanga\\Desktop\\note.txt","rw");FileChannel channel = file.getChannel();ByteBuffer buffer = ByteBuffer.allocate(1024);channel.read(buffer);buffer.flip();byte[] res = new byte[1024];buffer.get(res,0,buffer.limit());System.out.println(new String(res));channel.close();
We look at this piece of code, this code I roughly divided into four parts, the first part to get the file channel, the second part to allocate buffers and complete the read operation, the third part of the buffer in the data to print, the fourth part of the closed channel connection.
The first part:
The Getchannel method is used to obtain a file-related channel instance, which is implemented as follows:
public final FileChannel getChannel() { synchronized (this) { if (channel == null) { channel = FileChannelImpl.open(fd, path, true, rw, this); } return channel; }}
public static FileChannel open(FileDescriptor var0, String var1, boolean var2, boolean var3, Object var4) { return new FileChannelImpl(var0, var1, var2, var3, false, var4);}
The Getchannel method calls Filechannelimpl's factory method to build a Filechannelimpl instance, and Filechannelimpl is a subclass implementation of the abstract class FileChannel.
The necessary parameters that make up the Filechannelimpl instance are the file pointers to the file, the full path of the file, read and write permissions, and so on.
Part II:
The basic structure of the Buffer we have introduced the above, and here no longer repeat, the so-called buffer, is essentially a byte array.
public static ByteBuffer allocate(int capacity) { if (capacity < 0) throw new IllegalArgumentException(); return new HeapByteBuffer(capacity, capacity);}
The build of the Bytebuffer instance is generated through the factory pattern, and the parameter capacity must be specified as the capacity of the internal byte array. Heapbytebuffer is the memory on the heap of the virtual machine, all the data will be stored in the heap space, and we will shortly introduce it to a brother, Directbytebuffer, which is allocated in the heap outside of memory, the specific one will say.
The structure of this heapbytebuffer we might as well go inside and see:
HeapByteBuffer(int cap, int lim) { super(-1, 0, lim, cap, new byte[cap], 0);}
Call the constructor of the parent class to initialize some of the property values we mentioned in Bytebuffer, such as Position,capacity,mark,limit,offset and byte array hb.
Next, let's look at the call chain of this read method.
This read method is a subclass of Filechannelimpl that overrides the FileChannel read method of the parent class. This method is not the core of the read operation, we briefly summarize that the method will first get the current channel instance of the lock, if not occupied by other threads, then occupy the lock, and call Ioutil's Read method.
Ioutil's Read method inside also called a lot of methods, some even local methods, here is simply a brief introduction to the entire Read method of the general logic, the details left to everyone to learn.
First judge whether our Bytebuffer instance is a directbuffer, that is to say whether the current Bytebuffer instance is allocated in direct memory, and if so, the readintonativebuffer will be called Method reads the data from the disk directly into the direct memory where the Bytebuffer instance resides.
Otherwise, the virtual machine allocates a piece of memory in the direct memory area, and the first address of the memory region is stored in the Address property of the VAR5 instance.
The data is then read from the disk into the direct memory area represented by VAR5.
Finally, the put method writes data from the direct memory area represented by VAR5 to the in-heap buffer represented by VAR1 and frees the temporary created direct memory space.
In this way, our incoming buffers are successfully read into the data. Write operation is the opposite, we can be the analogy, anyway, the heap of data to reach the disk will have to go through the memory of the outside of the replication process.
The third part is relatively simple, here no longer repeat. To remind you that you want to better use this channel and buffer for file read and write operations, you have to the buffer of several variables of the value of the moment to hold, position and limit the current value is what, roughly what position, must be clear, otherwise this read-write coexistence of the buffer may be confusing you.
Selector Selector
Selector is a component of Java NIO that listens to various states of multiple channel for managing multiple channel. But in essence, because FileChannel does not support registering selectors, Selector is generally considered to serve the network socket channel.
And everyone's mouth of the "nio is non-blocking", to be precise, refers to the network programming in the client-server connection Exchange data process is non-blocking. Normal file read and write is still blocked, and IO is the same, this may be a lot of beginners will be ignorant, including I also always wondered why the NIO file read and write non-blocking, obviously is blocked.
Creating a selector is generally done by Selector's factory method, Selector.open:
Selector selector = Selector.open();
A channel that wants to register to a selector must adjust the mode to non-blocking mode, for example:
//创建一个 TCP 套接字通道SocketChannel channel = SocketChannel.open();//调整通道为非阻塞模式channel.configureBlocking(false);//向选择器注册一个通道SelectionKey key = channel.register(selector, SelectionKey.OP_READ);
The above code is to register a channel to the simplest version of the selector, the channel that supports the registration selector has a register method, which is used to register the current instance channel to the specified selector.
The first parameter of the method is the target selector, and the second parameter is actually a binary mask that indicates which events of the current selector are of interest to the current channel. The following values are provided as enumeration types:
- int op_read = 1 << 0;
- int op_write = 1 << 2;
- int op_connect = 1 << 3;
- int op_accept = 1 << 4;
This mechanism, which uses binary masks to represent certain States, is also encountered when it comes to describing the structure of a virtual machine class file, which is a bits to describe a state.
The Register method returns an Selectionkey instance that represents an association between the selector and the channel. You can call its Selector method to return the currently associated selector instance, or you can call its channel method to return the tunnel instance in the current association relationship.
In addition, Selectionkey's Readyops method returns an integer value, which is a binary mask, that will return the currently selected set of events in the event of interest in the current channel.
For example:
int readySet = selectionKey.readyOps();
If the value of Readyset is 13, the binary "0000 1101", from the backward forward number, the first bit is 1, the third bit is 1, the fourth bit is 1, then the channel associated with the selector, read ready, write ready, connection ready.
So, when we register a channel to the selector, we can listen to the various events of the channel through the returned Selectionkey instance.
Of course, once multiple channels are registered in a selector, it is not possible for one to record the Selectionkey instances returned when registering them to listen for channel events, and the selector should have methods to return all successful channel-related Selectionkey instances.
Set<SelectionKey> keys = selector.selectedKeys();
The Selectedkeys method returns a collection of Selectionkey instances of all channels registered successfully in the selector. Through the Selectionkey instance of this set, we can get the event readiness of all the channels and handle the operation accordingly.
Here we apply the above theoretical knowledge with a simple example of client server connection communication:
Service-Side code:
The actual effect of the operation of this small program is such that the client set up the request to the server, waiting for the request to be fully established, the client will check whether there is data writeback service side, and the service side of the task is very simple, accept any client's request to connect and write back a piece of data.
Although the whole process is very simple, but as long as you have a little vague place, you this function is impossible to achieve, do not believe you try, especially add the selector of the client code, more worthy of a line of analysis. As a reminder, you should be more concerned about which methods are blocked and which are non-blocking, which can help you analyze your code.
This is actually a most simple server client request model, understand this will help to understand the browser and Web server working principle, here I will no longer take you to analyze, there are any different views of the Welcome to my message, we learn to discuss together.
Presumably you can also find that the code added to the selector is much more complex, and not necessarily efficient in the original code, this is because your function is relatively simple, does not involve a lot of channel processing, logic once complex, the advantages of the selector will be very obvious.
In fact, there is an AIO in NIO, that is, asynchronous IO is not introduced, because asynchronous IO involves a lot of other aspects of knowledge, here for the time being no introduction, the next article will be a separate description of the asynchronous task and other related content.
All the code, pictures, and files in the article are stored on my GitHub:
(Https://github.com/SingleYam/overview_java)
Welcome to the public number: in the code of the high-base, all the articles will be synchronized in the public number.
Detailed Java NIO