DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • Architecture and Code Design, Pt. 2: Polyglot Persistence Insights To Use Today and in the Upcoming Years
  • Implement a Distributed Database to Your Java Application
  • Protecting Your Domain-Driven Design from Anemia
  • Rails 6: Multiple DB Support

Trending

  • Exploring Edge Computing: Delving Into Amazon and Facebook Use Cases
  • Send Your Logs to Loki
  • The Systemic Process of Debugging
  • Mastering Persistence: Why the Persistence Layer Is Crucial for Modern Java Applications
  1. DZone
  2. Software Design and Architecture
  3. Cloud Architecture
  4. Java NIO vs. IO

Java NIO vs. IO

Jakob Jenkov user avatar by
Jakob Jenkov
·
Aug. 28, 11 · Analysis
Like (19)
Save
Tweet
Share
131.49K Views

Join the DZone community and get the full member experience.

Join For Free

when studying both the java nio and io api's, a question quickly pops into mind:

when should i use io and when should i use nio?

in this text i will try to shed some light on the differences between java nio and io, their use cases, and how they affect the design of your code.

main differences of java nio and io

the table below summarizes the main differences between java nio and io. i will get into more detail about each difference in the sections following the table.

io nio
stream oriented buffer oriented
blocking io non blocking io
selectors

stream oriented vs. buffer oriented

the first big difference between java nio and io is that io is stream oriented, where nio is buffer oriented. so, what does that mean?

java io being stream oriented means that you read one or more bytes at a time, from a stream. what you do with the read bytes is up to you. they are not cached anywhere. furthermore, you cannot move forth and back in the data in a stream. if you need to move forth and back in the data read from a stream, you will need to cache it in a buffer first.

java nio's buffer oriented approach is slightly different. data is read into a buffer from which it is later processed. you can move forth and back in the buffer as you need to. this gives you a bit more flexibility during processing. however, you also need to check if the buffer contains all the data you need in order to fully process it. and, you need to make sure that when reading more data into the buffer, you do not overwrite data in the buffer you have not yet processed.

blocking vs. non-blocking io

java io's various streams are blocking. that means, that when a thread invokes a read() or write(), that thread is blocked until there is some data to read, or the data is fully written. the thread can do nothing else in the meantime.

java nio's non-blocking mode enables a thread to request reading data from a channel, and only get what is currently available, or nothing at all, if no data is currently available. rather than remain blocked until data becomes available for reading, the thread can go on with something else.

the same is true for non-blocking writing. a thread can request that some data be written to a channel, but not wait for it to be fully written. the thread can then go on and do something else in the mean time.

what threads spend their idle time on when not blocked in io calls, is usually performing io on other channels in the meantime. that is, a single thread can now manage multiple channels of input and output.

selectors

java nio's selectors allow a single thread to monitor multiple channels of input. you can register multiple channels with a selector, then use a single thread to "select" the channels that have input available for processing, or select the channels that are ready for writing. this selector mechanism makes it easy for a single thread to manage multiple channels.

how nio and io influences application design

whether you choose nio or io as your io toolkit may impact the following aspects of your application design:

  1. the api calls to the nio or io classes.
  2. the processing of data.
  3. the number of thread used to process the data.

the api calls

of course the api calls when using nio look different than when using io. this is no surprise. rather than just read the data byte for byte from e.g. an inputstream, the data must first be read into a buffer, and then be processed from there.

the processing of data

the processing of the data is also affected when using a pure nio design, vs. an io design.

in an io design you read the data byte for byte from an inputstream or a reader. imagine you were processing a stream of line based textual data. for instance:

name: anna
age: 25
email: anna@mailserver.com
phone: 1234567890

this stream of text lines could be processed like this:

inputstream input = ... ; // get the inputstream from the client socket

bufferedreader reader = new bufferedreader(new inputstreamreader(input));

string nameline   = reader.readline();
string ageline    = reader.readline();
string emailline  = reader.readline();
string phoneline  = reader.readline();

notice how the processing state is determined by how far the program has executed. in other words, once the first reader.readline() method returns, you know for sure that a full line of text has been read. the readline() blocks until a full line is read, that's why. you also know that this line contains the name. similarly, when the second readline() call returns, you know that this line contains the age etc.

as you can see, the program progresses only when there is new data to read, and for each step you know what that data is. once the executing thread have progressed past reading a certain piece of data in the code, the thread is not going backwards in the data (mostly not). this principle is also illustrated in this diagram:

java io: reading data from a blocking stream.
java io: reading data from a blocking stream.

a nio implementation would look different. here is a simplified example:

bytebuffer buffer = bytebuffer.allocate(48);

int bytesread = inchannel.read(buffer);

notice the second line which reads bytes from the channel into the bytebuffer. when that method call returns you don't know if all the data you need is inside the buffer. all you know is that the buffer contains some bytes. this makes processing somewhat harder.

imagine if, after the first read(buffer) call, that all what was read into the buffer was half a line. for instance, "name: an". can you process that data? not really. you need to wait until at leas a full line of data has been into the buffer, before it makes sense to process any of the data at all.

so how do you know if the buffer contains enough data for it to make sense to be processed? well, you don't. the only way to find out, is to look at the data in the buffer. the result is, that you may have to inspect the data in the buffer several times before you know if all the data is inthere. this is both inefficient, and can become messy in terms of program design. for instance:

bytebuffer buffer = bytebuffer.allocate(48);

int bytesread = inchannel.read(buffer);

while(! bufferfull(bytesread) ) {
    bytesread = inchannel.read(buffer);
}

the bufferfull() method has to keep track of how much data is read into the buffer, and return either true or false, depending on whether the buffer is full. in other words, if the buffer is ready for processing, it is considered full.

the bufferfull() method scans through the buffer, but must leave the buffer in the same state as before the bufferfull() method was called. if not, the next data read into the buffer might not be read in at the correct location. this is not impossible, but it is yet another issue to watch out for.

if the buffer is full, it can be processed. if it is not full, you might be able to partially process whatever data is there, if that makes sense in your particular case. in many cases it doesn't.

the is-data-in-buffer-ready loop is illustrated in this diagram:

java nio: reading data from a channel until all needed data is in buffer.
java nio: reading data from a channel until all needed data is in buffer.


summary

nio allows you to manage multiple channels (network connections or files) using only a single (or few) threads, but the cost is that parsing the data might be somewhat more complicated than when reading data from a blocking stream.

if you need to manage thousands of open connections simultanously, which each only send a little data, for instance a chat server, implementing the server in nio is probably an advantage. similarly, if you need to keep a lot of open connections to other computers, e.g. in a p2p network, using a single thread to manage all of your outbound connections might be an advantage. this one thread, multiple connections design is illustrated in this diagram:

java nio: a single thread managing multiple connections.
java nio: a single thread managing multiple connections.

if you have fewer connections with very high bandwidth, sending a lot of data at a time, perhaps a classic io server implementation might be the best fit. this diagram illustrates a classic io server design:

java io: a classic io server design - one connection handled by one thread.
java io: a classic io server design - one connection handled by one thread.

from http://tutorials.jenkov.com/java-nio/nio-vs-io.html

Java (programming language) Data (computing) Buffer (application) Database Stream (computing) Design Processing Connection (dance)

Opinions expressed by DZone contributors are their own.

Related

  • Architecture and Code Design, Pt. 2: Polyglot Persistence Insights To Use Today and in the Upcoming Years
  • Implement a Distributed Database to Your Java Application
  • Protecting Your Domain-Driven Design from Anemia
  • Rails 6: Multiple DB Support

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: