Basic knowledge of Java NIO

Source: Internet
Author: User

Objective

The preface part is the science popularization, the reader can choose whether to read this part content.

Why do we need to care about NIO? I think a lot of business apes will have this question.

I was in the first two years of work on this issue is also very puzzled, because at that time I think I am very familiar with IO operation, read and write files are very slip, IO package is nothing more than file, Randomaccessfile, byte stream, character stream these, feel no good tangled. The most chaotic is the inputstream/outputstream of a lot of classes do not know who is who, but after understanding the decorator mode, it is easy to crack.

In the Java realm, the general file operation really only needs to deal with the java.io package, especially for the programmer who writes the business code. However, when you write a two or three-year code, your business code may have been written very slip, blindfolded can also write additions and deletions to change the search. At this point, you might want to start learning more about the underlying content, including concurrency, JVMS, distributed systems, and source code implementations for each open source framework, and programmers at this stage will begin to recognize the usefulness of NIO because communication between systems is ubiquitous.

Maybe a lot of people don't know what's the use of Netty or Mina? What's the difference from Tomcat? Why do I need to use Netty when I use HTTP requests to solve the problem of inter-application calls?

The answer to these questions, of course, is simply to improve performance. Does it mean that Tomcat is not performing well? Of course not, they are not used in the same scenario. At the beginning I did not know what the Nginx in front of Tomcat, but also through the practice of slowly understanding the meaning.

Nginx is a Web server, Tomcat/jetty is an application server, Netty is a communication tool.

Maybe you don't know what NIO is for now, but don't give up learning it.

Buffer operation

The buffer is the core of the NIO operation, essentially the NIO operation is the buffer operation.

The write operation is to drain the data from the buffer, such as persisting data from the buffer to disk.

The read operation is to populate the buffer with data so that the application can use the data later.

Of course, the buffer we are talking about here refers to the buffer of the user space.

.

Simple analysis. After the application makes a read operation, the kernel sends commands to the disk controller, requiring the disk to return the data, and the disk controller sends the data directly to the kernel buffer via DMA. Once the kernel buffer is full, the kernel copies the data to the buffer specified by the process requesting the data.

Dma:direct Memory Access

Wikipedia: Direct memory access is a memory access technology in computer science. It allows the internal hardware subsystem (computer peripherals) of some computers to read and write directly to the system memory independently, without the need for the central processing Unit (CPU) to intervene. DMA is a fast way of data transfer with the same level of processor burden. Many hardware systems use DMA, including hard disk controllers, graphics cards, network cards, and sound cards.

In other words, the disk controller can write data from disk to memory without the help of the CPU, after all, it is a waste to let the CPU wait for IO operation to complete.

It's easy to see that the data comes first to the kernel and then the kernel to the user space buffer is not efficient, so let's simply say why you need to design it.

    • First, the user space code is not directly access to hardware, the kernel space to be responsible for and hardware communication, kernel space is controlled by the operating system.

    • Second, the disk stores a fixed-size block of data, the disk according to the sector to organize the data, and the user process is generally requested by a block of arbitrary size, so the kernel should be responsible for coordination, the kernel is responsible for assembling and disassembling data.

The kernel space caches and pre-reads the data, so if the user process needs data that is just in kernel space, it can be copied directly. If the kernel space does not have the data required by the user process, the user process needs to be suspended, waiting for the data to be ready.

Virtual memory

This concept everyone knows, here continue to wordy, virtual memory is a computer system memory management of a technology. The buffer operation in front of it seems simple, but concrete to the bottom details, or quite complex.

The following description, I try to ensure accurate, but will not be too specific, because the virtual memory is quite complex, to fully introduce clearly, I am afraid that a large amount of space, if the reader is interested in this aspect of the content, it is recommended that readers look for more professional and comprehensive information, such as "in-depth understanding of computer systems."

Physical memory is organized into a large array, each cell is a byte size, and then each byte has a unique physical address, which should be well understood.

Virtual memory is an abstraction of physical memory, which allows an application to assume that it has its own contiguous available memory (a contiguous, complete address space), and in fact, all the memory the application gets is actually an illusion, which is usually separated into multiple pieces of physical memory (the page that follows), There are also parts that are temporarily stored on external disk storage and swapped in and out when needed.

For example, in a 32-bit system, the memory that each application can access is 4G (the maximum addressable space for a 32-bit system 2^32), where 4G is virtual memory, and each program thinks it has contiguous 4G of memory, even if our computer has only 2G of physical memory. That is, for multiple applications running concurrently on a machine, each program thinks it can get a continuous 4G of memory. The middle of this is the use of virtual memory.

Conceptually, virtual memory is also organized into a large array, each of which is a byte size, with a unique virtual address for each byte. It is stored on disk, and physical memory is its cache.

Physical memory as a cache of virtual memory, of course, is not organized in bytes, so inefficient that it is cached between pages (page). Virtual memory is divided into virtual pages, physical memory is also divided into a physical page, the size of the two pages should be consistent, usually 4kb-2mb.

As an example, look at:

.

Process 1 now has 8 virtual pages, 2 of which are cached in main memory, 6 are still on disk, and then read into the main store when needed, and process 2 has 7 virtual pages, 4 of which are cached in main memory and 3 are still on disk.

When the CPU reads the memory data, the virtual address is given, and the task of translating a virtual address into a physical address is what we call address translation. The query table in main memory holds the mapping relationship of virtual address to physical address, and the contents of the table are maintained by the operating system. When the CPU needs to access memory, a hardware called a memory management unit on the CPU will first query the actual physical address and then read the data to the specified physical address.

The query table mentioned above, we call the page table, the virtual memory system through the page table to determine whether a virtual page has been slow to exist in main memory. If it is, the page table will be responsible for the mapping of the physical page, if not hit, that is, we often see the concept of missing pages, the corresponding English is page fault, the system first determine where the virtual page resides in the disk, and then select a sacrifice page in physical memory, and copy the virtual page from the disk into memory, Replace this sacrifice page.

The activity of transferring pages between disk and memory is called switching (swapping) or page scheduling (paging).

Below, a brief introduction to the benefits of virtual memory.

SRAM cache: Represents the L1, L2, and L3 caches that are located between the CPU and main memory.

DRAM cache: Represents the cache of virtual memory systems, caching virtual pages into main memory.

Physical memory accesses are about 10 times times slower than the cache, while disks are about 100,000 times times slower than physical memory. Therefore, DRAM cache misses are much more expensive than SRAM cache misses, because once the DRAM cache is not hit, it is necessary to load the virtual pages to disk. The SRAM cache misses and is usually served by the main memory of DRAM. The time overhead of reading the first byte from one sector of the disk is about 100,000 times times slower than reading the contiguous bytes in this sector.

Readers who understand Kafka should know that sequential storage of messages on disk is critical to the performance of Kafka.

The conclusion is that the performance of IO is mainly determined by whether the DRAM cache is hit.

Memory-Mapped files

The English name is Memory Mapped Files, I believe you have heard this concept, in many of the requirements of high IO performance Java applications will be used, it is the support provided by the operating system, after we introduce the NIO Buffer will encounter the Mappedbytebuff Er is used to support this feature.

What is it:

We can assume that the memory-mapped file is a special kind of file, and our Java program can read the contents of the file directly from memory. It is implemented by mapping portions of the entire file or file to memory pages, and the operating system is responsible for loading the required pages, so it is very fast.

Advantage:

    • Once we have written the data into a memory-mapped file, even if our JVM hangs up, the operating system will still help us persist this part of the memory data to disk. Of course, if it is a power outage, it is still possible to lose data.

    • In addition, it is more suitable for processing large files, because the operating system only when we need the page is not in memory to load page data, and with its processing a large number of small files may cause frequent missing pages.

    • Another important advantage is memory sharing. We can use the same memory-mapped file in multiple processes at the same time, which is a way of collaborating between processes. Imagine the data communication between processes usually we use sockets to request, and memory sharing can bring at least 10 times times more performance improvement.

We haven't touched the NIO Buffer yet, so here's a quick hint:

Import Java.io.randomaccessfile;import Java.nio.mappedbytebuffer;import Java.nio.channels.filechannel;public class Memorymappedfileinjava {private static int count = 10485760;//10 MB public static void Main (string[] args) throws Except Ion {Randomaccessfile MemoryMappedFile = new Randomaccessfile ("LargeFile.txt", "RW");//Map file to memory, map method Mappedbytebuff Er out = Memorymappedfile.getchannel (). Map (FileChannel.MapMode.READ_WRITE, 0, Count); This step of the write operation is actually written into memory, do not directly manipulate the file for (int i = 0; i < count; i++) {Out.put ((byte) ' A ');} System.out.println ("Writing to Memory Mapped File is completed"); The read operation of this step reads memory for (int i = 0; i < i++) {System.out.print (char) out.get (i));} System.out.println ("Reading from Memory Mapped File is completed"); }}

One thing we should note is that the memory used to load the memory-mapped file is out-of-heap memory.

Reference: Why use Memory Mapped File or Mapppedbytebuffer in Java

Scatter/aggregate IO

Scatter/gather IO, personally think this looks cool, in practice is more difficult to use.

Scatter/Gather IO (another argument is that vectored I/O, or vector IO) is a way to input and output multiple buffers in a single operation, you can write data from multiple buffers to a single data stream, or you can read a single stream of data into multiple buffers.

.

.

This feature is supported by the operating system, and the Java NIO package has provided us with an operational interface. This operation can improve performance because one operation is equivalent to a number of linear operations, and this also provides atomic support, because if you operate with multithreading, there may be competition for the operation of the same file.

Non-blocking IO

It is believed that the reader has seen in many places that NIO does not represent New io, but non-blocking io, which we do not dwell on here. I think the reason for this is that it provides support for Non-blocking IO when the first NIO is introduced in Java 1.4.

Before we understand the non-blocking IO, we must first understand that its opposite blocking mode is bad.

For example, Inputstream.read this method, once a thread calls this method, it will always block here until the data transfer is complete, return 1, or throw an exception due to other errors.

We take the Web server, blocking mode, each network connection, we need to open a thread to read the request data, and then to the back-end processing, processing the end of the data to write back to the network connection, the entire process needs a separate thread to do this. That means that once the number of requests is higher, a large number of threads will have to be created, and a large number of threads will inevitably lead to the overhead of creating threads, switching threads, and more importantly, allocating a portion of memory to each thread, which can cause memory to be exhausted quickly. We say that multithreading is a powerful tool, but this is where too many threads cause the system to completely digest.

In general, we can divide io into two categories: IO for data blocks (block-oriented) and IO for stream (stream-oriented). For example, the reading and writing of a file is oriented to the data block, reading the keyboard input or writing data to the network is flow-oriented.

Note that this verse is mixed with the two words of flow and passage, and it is hoped that the reader will not be bothered by this.

Stream-oriented IO tends to be slower, such as slower network speeds and the need to wait for new input from users.

At this point, we can use a thread to handle multiple streams, and this thread is responsible for polling the state of those streams all the time, and when some flow has data coming, it can handle the data, and the other child threads will be able to handle it, and the thread continues polling.

The problem is that continuous polling also leads to a waste of resources, especially when a thread needs to poll a lot of traffic.

Modern operating system provides a function called readiness selection, we let the operating system to monitor all the channels in a collection, when some of the channel data is ready, you can directly to the channel to obtain data. Of course, the operating system will not notify us, but when we go to the operating system, it will know that the channel N is ready, and we don't need to poll ourselves (we'll see the Select and poll on our own polling later).

We will talk about Java NIO in the back of the Selector, corresponding class Java.nio.channels.Selector, this is the Java Readiness Selection support. In this way, one of our threads can manage multiple channels more efficiently.

.

The above diagram I think you may have seen, is to use a Selector to manage multiple Channel, to achieve a thread to manage multiple connections. In the final analysis, we have solved the problem that we mentioned earlier that the blocking mode thread creation is too large.

In Java, the subclass that inherits from Selectablechannel is implemented non-blocking IO, we can see the main have socket IO in the Datagramchannel and Socketchannel, and FileChannel does not inherit It. Therefore, file IO is not supported for nonblocking mode.

In the implementation of the system, POSIX provides two ways of select and poll. The two biggest differences are in the number of handles held, select supports only up to fd_setsize (typically 1024), and obviously many scenarios exceed this number. And poll how much we want to create. They all have a common disadvantage, that is, when a task is completed, we can only know that a few tasks have been completed, and do not know the specific handle, so we need to do a scan.

Because of the shortcomings of select and poll, the following implementations have been spawned. There are/dev/poll in Kqueue,solaris in bsd& OS X, and Epoll in Linux.

Windows does not provide an additional implementation and can only use SELECT.

On different operating systems, the JDK chooses the non-blocking implementation supported by the corresponding system.

Asynchronous IO

We know that Java 1.4 introduces new IO, starting with Java 7, which is no longer new IO, but more new IO coming, which we also call NIO2.

The biggest change that Java7 brings to NIO should be the introduction of asynchronous IO (asynchronous IO). Originally, asynchronous IO was already on the agenda, but the big boys didn't have time to finish, so they dragged it to Java 7. Needless to say, simply take a look at what asynchronous IO is.

To say what asynchronous Io is, of course, you have to start with a problem that non-blocking IO does not solve. Non-blocking IO works well, it solves the latency problem of blocking IO, but its disadvantage is that we need to poll to get the results.

Asynchronous IO solves this problem by simply initializing the thread, providing a callback method, and then doing something else. When the data is ready, the system is responsible for invoking the callback method.

The main feature of asynchronous IO is the callback, which is also very common in our daily code.

The simplest way to do this is to design a thread pool in which the threads in the pool are responsible for blocking operations, and once an operation is completed, the callback method is called. For example, in a Web server, we've already said that we can't open a new thread for every request, we can design a pool of threads to take on a thread to receive requests, and then hand over the task to the thread pool and provide a callback method so that the thread can do the other things. If you continue to process other requests. When the task is completed, the thread in the pool can call the callback method to notify.

Another way is not to design a thread pool, let the operating system to help us achieve. The process is basically the same, provided to the operating system callback method, then can do other things, and so on, the operating system will be responsible for callbacks. The disadvantage of this approach is that it relies on the specific implementation of the operating system, but it also has some advantages.

First of all, we design our own thread pool to handle the task, we need to grasp the size of the thread pool, not too big, not too small, which often requires our experience, and secondly, the operating system to do this thing, the operating system can help us in some scenarios to optimize performance, such as file IO Process to help find the data you need faster.

The implementation of the operating system for asynchronous IO also has a number of ways, mainly in the following 3:

    1. Linux AIO: Supported by a Linux kernel

    2. POSIX aio:linux,mac os X (now called Mac OS), Bsd,solaris and so on, is supported by GLIBC in Linux.

    3. Windows: Provides a mechanism called completion ports.

The author of this article asynchronous disk I/O says that in several system implementations of Unix-like, there are too many limitations, poor quality of implementation, and the use of thread pooling to manage asynchronous operations.

The implementation of asynchronous IO provided under Windows is somewhat different. It first lets threads in the thread pool go to the spin call getqueuedcompletionstatus.aspx) method to determine if it is ready. Then, let the task run, but you need to provide specific parameters to tell the thread executing the task so that the thread executes and notifies the thread pool of the result. Once the task is complete, the operating system wakes up threads in the thread pool that are blocking the GetQueuedCompletionStatus method, allowing them to perform subsequent results processing.

Windows intelligently wakes up the threads that execute the GetQueuedCompletionStatus method to keep the number of active threads in the thread pool at a reasonable level. This will not create too many threads and reduce the overhead of thread switching.

Java 7 on the implementation of asynchronous IO, if it is Linux or other Unix-like systems, is implemented using a self-built thread pool, if it is on the Windows system, is implemented by the system-provided completion ports.

So, what should we choose between non-blocking IO and asynchronous IO?

If it is file IO, we have no choice but to select asynchronous IO.

In the case of Socket IO, under Unix-like systems we should choose to use non-blocking io,netty based on nonblocking mode; we should use asynchronous IO in Windows.

Of course, the existence of Java is to achieve platform-independent, so, in fact, we do not need to choose, understand these rights when you let yourself up a bit of knowledge.

Summarize

As with several other articles, there is nothing to summarize, to say all in the text, I hope readers can learn something.

If it is wrong, I think it is normal, I write all these years are Java, for the bottom of the less understanding, so if the reader found that there is something unreasonable content, very much hope that the reader can come forward.

Basic knowledge of Java 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.