O'Reilly logo

Java Performance: The Definitive Guide by Scott Oaks

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 12. Java SE API Tips

This chapter covers areas of the Java SE API which have implementation quirks that affect their performance. There are many such implementation details throughout the JDK; these are the areas where I consistently uncover performance issues (even in my own code).

Buffered I/O

When I joined the Java performance group in 2000, my boss had just published the first ever book on Java performance, and one of the hottest topics in those days was buffered I/O. Fourteen years later, I was prepared to assume the topic was old hat and leave it out of this book. Then, in the week I started this book’s outline, I filed bugs against two unrelated projects where unbuffered I/O was greatly hampering performance. A few months later as I was working on an example for this book, I scratched my head as I wondered why my “optimization” was so slow. Then I realized: stupid, you forgot to buffer the I/O correctly.

So let’s talk about buffered I/O performance. The InputStream.read() and OutputStream.write() methods operate on a single character. Depending on the resource they are accessing, these methods can be very slow. A FileInputStream that uses the read() method will be excruciatingly slow: each method invocation requires a trip into the kernel to fetch one byte of data. On most operating systems the kernel will have buffered the I/O and so (luckily) this scenario doesn’t trigger a disk read for each invocation of the read() method. But that buffer is held in the kernel, not ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required