Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stream oriented IO vs Block Oriented IO

Tags:

java

io

nio

Java has stream oriented IO(java.io.) and Block oriented IO(java.nio.). How does block oriented IO improve the performance of IO?

like image 625
Chander Shivdasani Avatar asked Feb 27 '26 21:02

Chander Shivdasani


2 Answers

Primarily by reducing the need for copying. Since the stream-oriented APIs have to move everything into managed Java variables, the system has to copy all of the data you deal with. When you use the NIO libraries, Java can directly map in the OS I/O pages without having to make copies (and deal with allocation and garbage collection).

like image 125
chrylis -cautiouslyoptimistic- Avatar answered Mar 01 '26 09:03

chrylis -cautiouslyoptimistic-


The stream-based I/O uses streams to transfer data between a data source/sink and a Java program. The Java program reads from or writes to a stream a byte at a time. This approach to performing I/O operations is slow. The New Input/Ouput (NIO) solves the slow speed problem in the older stream-based I/O.

enter image description here

In NIO, you deal with channels and buffers for I/O operations.

A channel is like a stream. It represents a connection between a data source/sink and a Java program for data transfer.

enter image description here

There is one difference between a channel and a stream.

  • A stream can be used for one-way data transfer. That is, an input stream can only transfer data from a data source to a Java program; an output stream can only transfer data from a Java program to a data sink.
  • However, a channel provides a two-way data transfer facility.

You can use a channel to read data as well as to write data. You can obtain a read-only channel, a write-only channel, or a read-write channel depending on your needs.

like image 20
pardeep131085 Avatar answered Mar 01 '26 11:03

pardeep131085