Java.nio vs Java.io

Source: Internet
Author: User
Tags new set




Java.nio vs Java.ioby Nino Guarnacci on June 18, 2009

..... posted by Davide Pisano

This document was not a java.io or a Java.nio manual, or a technical document on java.io and Java.nio use. It is attempts to compare these, packages, highlighting differences and features in the very simple. Java.nio presents new stream communication aspects and inserts new buffer, file streaming and socket features.

java.io Overview

This are used for system input and output through data streams, and serialization. Streams support many different kinds of data, including simple bytes, primitive data types, localized characters, and Obje Cts. A stream is a sequence of DATA:A program uses an input stream to the read data from a source.

A program uses an output stream to write and send data to a destination:

Programs use byte streams to perform byte input and output. All byte stream classes extendsInputStream and outputstream.

About InputStream and OutputStream

Performing InputStream operations or outputstream operations means generally have a loop that reads the input stream and Writes the output stream one byte at a time. You can usebuffered I/O streams for a overhead reduction (overhead generated by each such request often triggers Disk access, network activity, or some other operation, which is relatively expensive). Buffered input streams read data from a memory area known as a buffer; The native input API is called only if the buffer is empty. Similarly, buffered output streams write data to a buffer, and the native output API are called only if the buffer is ful L. Those buffered API wrap the unbuffered streams:bufferedinputstream and Bufferedoutputstream.

File I/O

The above section focuses in streams, which provide a simple model for reading and writing data. Streams work with a large variety of data sources and destinations, including disk files. However, streams don ' t support all the operations is common with disk files. The following links give information on Non-stream file I/O. There is topics:

    • File is a class this helps to write platform independent code for examining and manipulating files and directories.

    • Random Access files support non sequential access to disk file data.

java.net socket

a socket is one endpoint of A two-way communication Link between programs running on the network. Socket classes is used to represent the connection between a client program and a server program. The java.net package provides the Classes:socket and ServerSocket. These implement the client side of the connection and the server side of the connection, respectively.

the client knows the host-name of the machine on which the server is running, and the port number on which the server is listening. Clients try to connect to the server and if everything goes well, the server accepts the connection. Upon acceptance, the server gets a new socket bound to the same local port and also have its remote endpoint set to the add Ress and port of the client. It needs a new socket so this it can continue to listen to the original socket for connection requests while tending to th E needs of the connected client.

The server waits for a client connection in blocking mode: serversocket.accept () is a blocking instruction, the server Waits for a connection and no other operation can is executed by the thread which runs the server. Because of this, the server can work in multitasking-implementing a multi-thread server:having to create a thread For every new socket created by the server.

NIO API

The I/O performance, often, is a modern application critical aspect. Operative Systems (OS) continuously improve the I/O performance. JVM provides a uniform operating environment that helps the Java programmer in most of the differences between operating-s Ystem environments. This makes it faster and easier to write, but the OS feature becomes hidden. To increase IO performance your could write a specific code to access the OS feature directly, but this isn ' t the best solu Tion-your code could be OS dependent. Java.nio provides new equipment to address this problem. IT provides high-performance I/O features to perform operations on commonly available commercial operating systems today.

The NIO packages of JDK 1.4 introduce a new set of abstractions for doing I/O.

Java.nio Overview

    • buffers for data of primitive types

    • character-set encoders and decoders

    • a pattern-matching facility based on Perl-style regular expressions

    • channels, a new primitive I/O abstraction

    • a file interface that supports locks and memory mapping

    • a multiplexed, non-blocking I/O facility for writing scalable servers

At the Sun site are it possible to find exhaustive technical documentation about Java.nio. Now I'll explain some of NiO ' s aspects to show the difference betwen the old library java.io. and Java.nio. Be advised, Java.nio was not a java.io substitute, rather it was a java.io ' expansion '. Nio's birth has caused a revision of Io's class and interface (look on thislink).

One of the most important aspects of NIO are the ability to operate in non-blocking mode, denied to the traditional Java i/ O Library. But what is non-blocking mode?

Non blocking mode

The bytes of an I/O stream must be accessed sequentially. Devices, printer ports, and network connections are common examples of streams.

Streams is generally, but not necessarily, slower than block devices, and is often the source of intermittent input. Most operating systems allow streams to being placed into non-blocking mode, which permits a process-to-check if input is AVA Ilable on the stream, without getting stuck if none are available at a given moment. Such a capability allows a process to handle input as it arrives but perform other functions while the input stream is IDL E. The operating system can be told to watch a collection of streams and indicate which of those streams is ready. This ability permits a process to multiplex many active streams using common code and a single thread by leveraging the RE Adiness information returned by the operating system. This is widely used on network servers to handle large numbers of network connections.

Buffers

Starting from the simplest and building-to-the most complex, the first improvement to mention is the set of Buffer Clas Ses found in the Java.nio package. These buffers provide a mechanism to store a set of primitive data elements in an in-memory container. A Bufferobject is a container for a fixed amount of data, a container where the data can be read and written.

All buffers is readable, but isn't all is writable. Each of the buffer class implements IsReadOnly () to indicate whether it would allow the buffer content to be modified.

Channels

Buffers work with channels. Channels is portals through which I/O transfers take place, and buffers is the sources or targets of those data transfer S. Data want to send are placed in a buffer, which are passed to a channel; Otherwise, a channel deposits data in a buffer you provide.

A Channel is like a tube this transports data efficiently between byte buffers and the entity on the other end of the Chan Nel. Channels is gateways through which the native I/O services of the operating system can be accessed with a minimum of over Head, and buffers is the internal endpoints used by channels to send and receive data.

Channels can operate in blocking or non-blocking modes. A Channel in non-blocking mode never puts the invoking thread to sleep. The requested operation either completes immediately or returns a result indicating that's nothing is done. Only stream-orientated channels, such as sockets can is placed in nonblocking mode. In the Java.nio channel family there is FileChannel, serversocketchannel and Socketchannel; These is specific channels created for file and socket management.

FileChannel

filechannels is read/write channels, they is Always blocking and cannot is placed into nonblocking mode. The nonblocking paradigm of stream-oriented I/O doesn ' t make as much sense for file-oriented operations because of the fun damentally different nature of file I/O.

filechannel objects cannot be created directly. A FileChannel instance can is obtained only by calling , Getchannel ()   on an open file object ( Randoma Ccessfile ,   fileinputstream , or F ileoutputstream ).   getchannel ()   method returns a  filechannel  object connected to the same file, with the same access permissions as the File object.  filechannel  objects is thread-safe. Multiple threads can concurrently call methods on the same instance without causing any problems and not all operations a Re multi-thread. Operations that affect the channel ' s position or the file size is single-threaded.

Using FileChannel, operations like file copy become a channel to channel Trasfer (transferTo ()and Transferfro M ()) and read/write operations become easy using buffers.

Socketchannel

Socketchannel is different to filechannel:the new sockets channels can operate in nonblocking mode and is selectable. It ' s no longer necessary to dedicate a thread to each socket connection, Using the new NIO classes, one or a few threads C An manage hundreds or even thousands of active sockets connections with little or no performance loss. It ' s possible to perform readiness selection of socket channels using a Selector object.

Socket channels can operate in nonblocking mode. The blocking nature of traditional Java sockets have traditionally been one of the most significant limitations to Java app Lication scalability. Non-blocking I/O is the basis upon which many sophisticated, and high-performance applications is built. Setting or resetting a channel ' s blocking mode is easy. Simply callconfigureblocking ().

nonblocking sockets is usually thought of for server-side use because they make it easier to manage many sockets Simultan eously.

Selector

Selectors provide the ability to has a channel readiness selection, which enables multiplexed I/O. To understand selector feature, I can explain selector advantage using the following example.

selection ke Y ). Instance there is only one controller for all three platforms.  He looks at the indicator ( Selec Tor.select () ) to the find out if a train have arrived and goes to meet that train.

It's simple to understand the advantages of using Selector:with a single thread you can obtain a multitasking application . As well as this, you can obtain more advantages using non-blocking selector! Imagine that the train controller looks at the Indicator:he can wait for a new train and does any of the other thing (blocking Mode using selector.select ()). But he can instead control tickets, for example, while waiting for a new train (non-blocking mode usingselector.select  Now ()). In the This is selector returns null and continue to execute code.

IO vs. NIO

NIO construction makes I/o faster than traditional I/O. In a program where the I/O operations constitute a significant amount of the processing, expect to see some difference. For example if an application have to copy files or transfer bytes using sockets, using Nio are possible to obtain a faster Performance because it is closer to the OS than the I/O API. Increasing the byte size, the difference becomes more appreciable. Nio also provides other features not in IO APIs, for streaming operations. However, it is not possible to substitute IO with NiO because NIO APIs adds functionalities to the java.io. NIO extends the native IO API introducing new possibilities for the developer to manipulate stream data in a powerful the.

References
    • JDK 6 Documentation
    • "JAVA NIO"-Ron hitchens-publisher:o ' Reilly

..... posted by Davide Pisano

Technorati Tag:java,java.nio,java.io

Java.nio vs Java.io

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.