JAVA IP principle

Source: Internet
Author: User

I/O problem is the core problem of the whole human-computer interaction, and it is an unavoidable problem for any programming language, because I/O is the main channel of machine acquiring and exchanging information. Often becomes a performance bottleneck. So Java has been doing continuous optimization on I/O, such as the introduction of NiO from JDK1.4, which improves I/O performance.

Summarize the following Java I/O operations classes:

Byte-based operation of I/O interfaces: InputStream and OutputStream

I/O interfaces based on character manipulation: writer and reader

Disk operation-based I/O interface: File

Network operation-based I/O interface: Socket

The first two groups are primarily data formats for transmitting data, and the latter two are primarily the means of transmitting data. Personally, the core issue of I/O is either that the data format affects I/O operations or that the transfer affects I/O operations. This is the core of I/O, which is where the data is written. I/O is just a means of interacting with machines or machines and machines, and in addition to being able to do this interactive function, we are concerned with how to improve its operational efficiency.

The various APIs for I/O are not discussed in detail here, and note that bytes and characters can be converted to and from each other by Streamdecoder and Streamencoder, which is actually an adapter design pattern.

5.1 How disk I/O works

Read and write file I/O operations are called interfaces provided by the operating system, because the disk device is managed by the operating system, and as far as Java is concerned, it is only a process that works as an application to access the physical device only by means of a system call. Read and write correspond to both read () and write () two system calls. As long as the system call can have the kernel space address and user space address switching problem, this is the operating system in order to protect the security of the system itself, the kernel program runs using memory space and user program run memory space isolation caused. However, while this guarantees the security of the kernel program, there is a certain problem that the data may be copied from the kernel space to the user space. Of course, the device drivers and operating systems that operate the disk also have a layer of file systems directly on it. This is not in-depth explanation.

If you encounter very time-consuming operations, such as disk I/O, the data is copied from the disk to the kernel space and then copied from the kernel space to the user space. In order to speed up I/O access, the operating system uses a caching mechanism in the kernel space, and if the user accesses the same disk address, the operating system returns the data from the kernel to the user program. Reduce I/O response time. In addition to some special cases, the page cache is transparently applied to all I/O, that is, every time the data is read from the disk, it must be accessed once and must be cached. So the second visit is faster. If the operating system is running all the time, the data on the disk will be cached forever as long as the memory is sufficient.

5.1.1 How to access files

1. Standard Access file mode

When the application calls the read () interface, the operating system checks the kernel's cache for any data that is needed, and if hit, returns directly. Otherwise, it is read from disk and then cached in the operating system's cache.

Writes, the user's application calls the Write () interface to copy the data from the user address space to the cache in the kernel address space. This is done for the user, and when it is written to the disk, it is determined by the operating system, unless the Sync Sync command is invoked. Corresponding to Java is the flush method.

2. Direct I/O mode

The so-called direct I/O approach is that the application application directly accesses the disk data without passing through the operating system kernel data buffer to reduce the data replication from the kernel buffer to the user program cache at a time. This approach is typically in the database management system implemented by the application in the management of the heap data. Because the operating system is not likely to know what is hot data, which data is accessed only once will not be accessed. However, direct I/O also has a negative effect, that is, if the cache is not hit, then each time the data will be loaded directly from the disk, this load is very slow.

5.1.2Java How to access the disk

We know that the only minimum description of the data on disk is the file, which means that the upper-level application can only manipulate the data on the disk through the file, which is the smallest unit of interaction between the operating system and the disk drive. It is worth noting that file in Java does not represent a real file object, it is just a virtual object representing the path, either a real file or a directory containing multiple files. The purpose of this design is not to care about whether the file really exists, but rather how it is done.

When will I really check if a file does not exist? is when you really want to read this file. The FileInputStream class is an interface that operates on a file, noting that a FileDescriptor object is created when a FileInputStream object is created. In fact, this FileDescriptor object is a description of a file object that truly represents an existence. When we manipulate a file object, we use the GETFD () method to get the file description associated with the underlying operating system that is actually operating.

Take a look at the file from disk as an example to introduce this process:

When a file path is passed in, a file object is created based on the path to identify the file, and then the object is created to actually read the file based on the files object, creating a FileDescriptor object that associates the actual disk file. This object allows you to control the disk file directly.

5.2 How network I/O works 5.2.1Java socket how it works

Sockets are an abstract feature that describes the communication between computers to accomplish each other. There are multiple sockets. In most cases, we use TCP/IP-based streaming sockets, which is a stable communication protocol.

Host A's application communicates with host B's application and must establish a connection through the socket, and the socket connection must be built with the underlying TCP/IP protocol to establish a TCP connection. Establishing a TCP connection requires the underlying IP protocol to address the hosts in the network. We know that the IP protocol used by the network layer can help us to locate the target host based on the IP address, but there may be multiple applications running on one host, and how to communicate with the specified application is specified by the TCP or UPD address, or the port number. This makes it possible for a Socket instance to uniquely represent a communication link for an application on a host.

5.2.2 Establishing a communication link

When the client wants to communicate with the server, the client first creates a socket instance, the operating system assigns the socket instance a local port number that is not used, and creates a socket data structure that contains local and remote addresses and port numbers. This data structure will remain in the system until the connection is closed. Before the constructor for the socket instance is returned correctly, the three-time handshake protocol for TCP will be made, and after the TCP handshake protocol is complete, the socket instance object will be created, otherwise the IOException exception will be thrown.

The corresponding server will create a ServerSocket instance, ServerSocket creation is simpler as long as the specified port number is not occupied, the general instance creation will succeed, and the operating system will create an underlying data structure for the ServerSocket instance. This data structure contains the port number of the specified listener and the wildcard character that contains the listening address, usually "*" which listens to all addresses. Then when the accept () method is called, it goes into a blocking state and waits for the client's request. When a new request arrives, a new socket data structure is created for the connection, which contains the address and port information for the requested source address and port. This newly created data structure will be associated to an incomplete list of connection data structures for the ServerSocket instance, and note that the server's corresponding socket instance is not created, and the socket instance of the server is not returned until the three handshake with the client is completed. and move the data structure of the Socket instance to the completed list in the never-complete list. Therefore, each data structure in the list associated with ServerSocket represents a TCP connection that is established with a client.

5.2.3 Data transfer

When the connection is successful, both the server and the client have a socket instance, and each socket instance has a InputStream and OutputStream, which are the two objects that exchange data. We also know that network I/O is transmitted by byte stream. When the Socket object is created, the operating system allocates a buffer of a certain size for InputStream and OutputStream, and the writing and reading of the data is done through this buffer. The write side writes the data to the outputstream corresponding SENDQ queue, and when the queue fills up, the data is sent to the RECVQ queue at the other end InputStream, and if the RECVQ is full then the OutputStream write method will Blocking until the RECVQ queue has enough space to hold the data sent by SENDQ. It is important to note that the size of this buffer and the speed of the write end and the speed of the read side greatly affect the data transfer efficiency of the connection, because of the possible blocking, so the network I/O and disk I/O in the data write and read also have a coordinated process, if both sides of the simultaneous transmission of data may produce a deadlock, NIO can avoid this situation.

Working mechanism of 5.2.4NIO

BIO blocks I/O, whether disk I/O or network I/O, which can be blocked when it is written to OutputStream or read from InputStream. Once the thread is blocked it will lose the use of the CPU, which is unacceptable in the case of current mass traffic and performance requirements. Although there are some workarounds for the current network I/O, such as a client one processing thread, a thread blocking when it is blocked but not affecting the other threads, and to reduce the overhead of the system thread, the thread pool approach is used to reduce the cost of threading creation and recycling, but there are still some usage scenarios that cannot be resolved. If some of the current needs of a large number of HTTP long connections, the server needs to maintain a millions of HTTP connection, but not every moment these connections are transmitting data, in this case it is not possible to create so many threads at the same time to maintain the connection. Even if the number of threads is not a problem, there are still some problems that cannot be avoided. In this case, we want to give some clients higher service priority, it is difficult to design the priority of the thread to complete, another situation is that we need to make each client's request on the server may need to access some competing resources, because these clients are in different threads, so need to synchronize, And often it is much more complex to achieve these synchronization operations than with single threads. All of these things indicate that we need another new I/O operation.

Here, for example, the communication between A and B is likened to the traffic between A and B. and the classes in bio and NiO can be likened to means of transportation. The Channel here is more specific than the Socket, which can be likened to a specific vehicle, such as a car or a high-speed rail, while Selector can run a dispatch system over a vehicle as a station, and it will be responsible for monitoring the current operating state of each vehicle: whether it is already in play or on the road, etc. That is, it can poll the status of each Channel. There is also a Buffer class, which is more specific than Stream, we can compare it to the seat on the car, the Channel is the car seat, the high-speed rail is the seat on the high-speed rail, it is always a specific concept, unlike stream. Stream can only represent a seat, as to what is the seat of your own imagination, that is, you do not know before going to the car, whether there is no seat on the vehicle, do not know what the car, because you can not choose, this information has been encapsulated in the Transport tool (Socket), is transparent to you. NIO introduced Channel, Buffer, and Selector to make this information concrete, giving programmers the opportunity to control them, such as: when we call write () to write data to SENDQ, when the data is written more than SENDQ length is required to follow the length of SENDQ segmentation, this process needs to have the user space data and the kernel address space to switch, and this switch is not you can control. In buffer, we can control the capacity of the buffer, and whether the expansion and how to expand can be controlled.

Call Selector's static factory to create a selector, create a service-side channel bound to a Socket object, and register the communication channel with the selector to set the communication channel to non-blocking mode. You can then call Selector's Selectedkeys method to check that all communication channels that have been registered on the selector are required to occur, and if an event occurs, all the Selectionkey will be returned, passing through this object channel Method can obtain the communication channel object so that the data can be read, and the data read here is buffer, this buffer is the buffer we can control.

In real-world applications, we typically place the events that listen for connection requests and the events that handle requests in two threads, one thread dedicated to listening to the client's connection request, and it is blocking, and the other thread is dedicated to processing the request, and the thread that specifically handles the request is actually using NIO, like a Web Server Tomcat and Jetty are all handled this way.

is to describe the processing of a Socket request based on the NIO working mode:

5.3 Java I/O design mode 5.3.1 Adapter mode

The role of an adapter is to adapt one interface to another, and there are many such requirements in the Java I/O class library, such as the conversion of string data byte data into a file.

Structure of the adapter pattern

Target (Destination interface): the interface to be converted

Adaptee (source role): interfaces that need to be adapted

Adapter (Adapter): To adapt the source interface to the target interface, inherit the source interface, achieve the target interface

Adorner mode in Java I/O

The InputStreamReader and OutputStreamWriter classes inherit the reader and writer interfaces respectively, but to create them, they must pass in a constructor with an instance of InputStream and OutputStream. The role of InputStreamReader and OutputStreamWriter is to adapt InputStream and OutputStream to reader and writer. Class structure of InputStreamReader

InputStreamReader class Structure

InputStreamReader implements the reader interface and holds the InputStream reference, which is held indirectly through the Streamdecoder class because it is encoded from byte to char.

Obviously the adapter is the InputStreamReader class, and the source role is InputStream, the target interface is Reader,outputstreamwriter is a similar way.

5.3.2 Decorator Mode

As the name implies, the decorator pattern is to enhance some functions on the basis of the original interface, similar to the proxy mode. For the user is transparent, users can not feel the decoration before and after the use of the difference.

Decorator Pattern Structure

Component: An abstract component role that defines a set of abstract interfaces that define the functions of this decorated component

Concretecomponent: Implement all the functions of this abstract component

Decorator: Decorator role, which holds a reference to an Component object instance, defines an interface that is consistent with the abstract component.

Concretedecorator: The specific decorator implementation, responsible for the implementation of the Decorator role definition function

Adorner mode in Java I/O

The use of the adorner pattern is described in the following example, FilterInputStream

InputStream class is the existence of abstract components, and FileInputStream is a specific component, it implements the abstract components of all interfaces, FilterInputStream class is the role of decoration, it implements the InputStream class all interfaces, and holds a reference to the object instance of InputStream. Bufferedinputstream is a specific adorner implementation, which gives the Inputsteam class additional functionality, which allows the Inpustream read data to be kept in memory for improved read performance.

JAVA IP principle

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.