Sunday, July 22, 2012

Handling I/O in Java

Handling input/output or I/O is one of the most common situations that programmers have to deal with. If you are writing a real world application, then you have to write a considerable amount of code to handle I/O regardless of the programming language or platform you’re going to use. Interestingly I/O plays a major role even in some of the simplest programs we can write. Even to write a standard ‘Hello World’ program in a language like Java or C, you need to know how to output characters to a console.
However, most developers often tend to ignore the importance and significance of I/O when writing code. Developers generally have an API level understanding of how to perform I/O operations using their main stream programming language. But they do not possess an in-depth understanding of how I/O works in the underlying system or how it can affect the performance and stability of the programs they write. Java developers in particular believe that knowing how to use the standard I/O API of Java is sufficient to write applications of good quality. Their lack of understanding on limitations and performance bottlenecks of the standard I/O API is astonishing. Most Java developers don’t have a firm grip on I/O coding best practices, third party I/O libraries available or relatively new concepts like NIO.
Last week I gave a talk at JAVA Colombo, the Sri Lankan JUG, trying to address some of the above issues. I started by giving a brief overview on I/O and I/O APIs in Java. I also introduced the NIO API and gave a short live demonstration of it comparing its performance to the standard I/O API of Java. Finally I discussed some of the best practices, patterns and anti-patterns related to writing I/O related code in Java. Full slide deck is now available on-line. Feel free to go through it send in your feedback.


Emmanuel L├ęcharny said...

Hi !

just wanted to correct your slide 36 : NIO is *not* faster than BIO. In fact, it's around 25% slower.

It has been demonstrated by Paul Tyma on this page :

Hiranya Jayathilaka said...

Hi Emmanuel,

Good to hear from you. You may not remember but we met a couple of years back at Amsterdam at an ApacheCon.

I agree with your points on some level. However in my experience, certain file I/O operations are much faster with NIO. In fact I did a live demo of a file copy operation during my presentation and showed how fast NIO can get.

I agree that certain (if not all) network I/O operations may not be as fast as we think in NIO. But still I find the multiplexed I/O concept in NIO quite fascinating.