Comparison of NiO and Io in Java

Source: Internet
Author: User
Tags socket blocking

Go : This article is not a user's manual for java.io or Java.nio, nor how to use the technical documentation for Java.io and Java.nio. This is just an attempt to compare the two packages, highlighting their differences and their respective features in the simplest way. Java.nio proposed a new stream communication concept and added a new buffer, file stream, and socket (socket) feature.

java.io Overview

This package implements the system input and output through the data flow and serialization mechanism. and supports multiple types of data streams, including simple bytes, native data types, region characters, and objects. A stream is a sequence of data: A program reads data from a source using an input stream;

Another program uses the output stream to write and send data to the destination.

These programs use byte streams to perform input and output of bytes. All classes that involve byte streams are inherited from InputStream and OutputStream.

About InputStream and OutputStream

The operation of InputStream and outputstream generally means that the bytes are read out or written to the output stream individually from the input stream. You can use buffered I/O streams to reduce I/o costs (where I/O requests often trigger disk access, network actions, or other costly operations). The buffered input stream reads the data from the buffered memory area and only calls the native input API (the local input stream provided by different operating systems api--the translator's note) only when the buffer is read. Similarly, buffered output streams write data to buffers, and only the buffer is full to invoke the native output API. These buffered APIs nicely encapsulate unbuffered streaming operations: Bufferedinputstream and Bufferedoutputstream.

File I/O

The above section is primarily for data flow, which provides a simple model of data reading and writing. The real data stream involves a wide variety of data sources and destinations, including disk files. However, the data flow does not support all disk file operations. The following links describe file I/O for non-data streams:

    • The file class can write platform-independent code that checks and processes files and directories.
    • The Random access files support non-serialized disk file data access.
java.net socket

Two-way communication links are established between programs running on the network, and the socket is one of the endpoints. A socket-related class represents a connection between a client program and a server-side program. The Java.net package offers two classes: socket and serversocket. They implement the client and server side of the connection respectively.

The client knows the domain name of the server running the machine, and the port it listens to, it tries to connect to the server, and if everything is OK, the server accepts and establishes the connection. When the connection is accepted, the server bindings a new socket on the listening port and notifies the remote endpoint to set the address and port of the client. A new socket is created to handle connected client requests while still listening to connection requests on the original socket.

The server waits for a client connection using blocking mode: Serversocket.accept () is a blocking instruction that the main thread cannot do any other action while the server waits for the connection to be accepted. For this reason, the server wants to achieve multitasking only by implementing a multithreaded server: each time a new socket is created, it is necessary to create a fresh thread for it.

NIO API

I/O performance is often a sore spot for a modern application. Operating system continuous optimization improves I/O performance, and the JVM also provides a set of operating environments to help Java programmers circumvent the majority of operating system I/O differences. All of these make I/O-related coding more efficient and simple, but it hides the operating system features. To enhance I/O performance, you can actually access the underlying functionality of the operating system with some special coding, but that is not the best solution-your code will have to rely on an operating system. The Java.nio package emerged to address this conundrum, providing high-performance I/O features and supporting most commonly used commercial operating systems today.

JDK1.4 's NIO package introduces an abstraction of a new series of I/O operations.

Java.nio Overview

Java.nio the new I/O API for the Java platform is implemented by this new package. The NIO API includes the following features:

    • Native type data buffering
    • Encoder and decoder for character sets
    • Pattern matching based on Perl-style regular expressions
    • Channel, a new native I/O abstraction concept
    • File interfaces that support lock and memory mapping
    • Scalable server architecture with multiplexed, non-blocking I/O capabilities

Detailed technical documentation for Java.nio can be found on the Sun (now Oracle) site. Here I will explain some of the concepts of NIO and compare it with the old java.io library. It is not recommended to treat Java.nio as a substitute for java.io, even if it is an "extension" of java.io. The birth of NiO led to a re-revision of the entire I/O class and interface (see details).
One of the most important concepts in NIO is running in nonblocking mode, completely different from the traditional Java I/O class library. What is non-blocking mode?

Non blocking mode non-blocking modes

The byte of an I/O stream must be serialized for access. A variety of devices, printer ports, network connections, etc. are common examples.
Data flow is often slower and often intermittent than a blocking device. Most operating systems allow data flow to be set to non-blocking mode, allowing the process to check if data is available on the stream, even if it does not cause the process to block. This mechanism allows the process to execute other logic when the input stream is idle, but it can be processed in a timely manner when the data arrives. The operating system can observe a bunch of data streams and indicate which ones are in the available state. By observing these available states, a process can use common encodings and a single thread to process multiple active streams at the same time. This is widely used when the network server handles a large number of network connections.

Buffers buffering

From a simple start, the first improvement is a series of new buffer classes in the Java.io package. These buffers provide a mechanism to store a heap of native types of data in a memory container. A buffer object is a fixed-capacity container in which data can be read and written.

All buffers are readable, but not all are writable. Each buffer class implements the IsReadOnly () method to indicate whether the buffered content is allowed to be modified.

Channels

Buffers need to be used with channel. The channel is the gateway to the I/O transmission, and the buffer is the source or destination of the data transfer. At the time of writing, the data you want to send is first buffered, then passed to a channel, and when read, the channel is responsible for receiving the data and then depositing it into the buffer you provide. (for example, the process of transmitting on the network: User data--send-side buffering--send-side channel--> network transmission--receive-side channel-->-buffered--user data, translator note)

The channel, like a pipe, transmits data efficiently between byte buffers on both sides of the pipeline. It is like a gateway, which can access the operating system's local I/O service with minimal cost, while the buffer is at the end of both ends and the channel uses it to send and receive data.

The channel can operate in non-blocking mode. A channel in non-blocking mode will not let the calling thread sleep. The requested action is either done immediately or returns a result informing you that nothing has been done. Only channel for data flow, such as sockets, can run in nonblocking mode. The channel in Java.nio includes FileChannel, Serversocketchannel, and Socketchannel, all of which are specific channel for file and socket management.

FileChannel

The FileChannel is a readable, writable channel that must be blocked and not used in nonblocking mode. Non-blocking styles for data flow I/O are not suitable for file-oriented operations, because file I/O is inherently different.

FileChannel objects cannot be created directly. An FileChannel instance can only be obtained by calling Getchannel () on an open file object (Randomaccessfile, FileInputStream, or FileOutputStream). The Getchannel () method returns a FileChannel object that is connected to the same file, with the same access rights as the file object. The FileChannel object is thread-safe. Multithreading can concurrently invoke methods on the same instance without causing any problems, but not all operations support multithreading. Operations that affect the channel location or file size must be single-threaded.

Using FileChannel, you can change operations such as copy to Channel to channel (TransferTo () and Transferfrom () methods), and read and write operations are easier to use buffering.

Socketchannel

Socketchannel differs from FileChannel: The new socket channel can be run in nonblocking mode and is selectable. It is no longer necessary to assign threads for each socket connection. With the new NiO class, one or more threads can manage hundreds or thousands of active socket connections, using only a small or even 0 performance penalty. Use the Selector object to select the available socket Channel.

There are 3 socket channel types: Socketchannel, Serversocketchannel, and Datagramchannel; Socketchannel and Datagramchannel are readable and writable, Serversocketchannel listen for incoming connections, and create new Socketchannel objects. All of these socketchannel will create an equivalent socket object (java.net sockets) when initialized. This equivalent socket can be retrieved from the channel object by invoking the socket () method. Each socket channel (in Java.nio.channels) object has a related Java.net.socket object, whereas not all socket objects have associated Channel objects. If you use the traditional way to create a socket object and initialize it directly, it will not have an associated channel object, and its Getchannel () method will return null.

The Socket channel is capable of running in non-blocking mode. The nature of traditional Java socket blocking has been one of the main culprits for the scalability of Java applications. Non-blocking I/O builds a lot of sophisticated, high-performance applications. setting or resetting the channel's blocking mode is simple, as long as you call Configureblocking ().

Non-blocking sockets are often used on the server side because it makes it easier to manage multiple sockets simultaneously.

Selector Selector

The selector (Selector) provides the ability to select the available state channel to enable multiplexing I/O. My example below will explain the advantages of the selector very well:

Imagine you are in a train station (Non-selector, non-selector scene) with 3 platforms (channels), each with a train arrival (buffer, buffer). Each platform has an administrator who manages the arriving train (worker thread, worker thread). This is a non-selector scenario. Now imagine the selector scenario. There are 3 platforms (channels), each platform will have a train arrival (buffer), each platform has an indicator (such as a bell) indicating "train arrival" (selection key). In this scenario, only one administrator can manage 3 of the platforms. He simply looks at the indicator (Selector.select ()) to determine if a train arrives and then handles the arrival train.

The advantage of understanding the selector scenario is simple: a single-threaded application that allows multitasking. In addition, the use of non-blocking selectors can also get more benefits! Imagine the train administrator looking at the indicator: he can wait for a new train to arrive without doing anything else (using Selector.select () blocking mode), or to sell a ticket while waiting for a new train to arrive (non-blocking mode using Selector.selectnow ()) This selector returns NULL to allow the thread to execute other code logic.

IO vs. NIO

NiO makes I/O more efficient than traditional I/O. In a program with a high percentage of I/O operations, think about what's different. For example, if an application needs to use a socket to copy files or transfer bytes, using NIO may result in faster performance because it is closer to the operating system than the I/O API. As the amount of data increases, the performance gains will be more impressive. In addition to the IO API, NIO also provides additional functionality for data flow operations. However, it is not possible to replace IO with NIO because the NIO API is based on the functionality extended on top of java.io. NiO brings new possibilities for developers to manipulate data streams in a more powerful way by extending the native IO API.

Comparison of NiO and Io in Java

Related Article

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.