O'Reilly logo

Java NIO by Ron Hitchens

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

Preface

Computers are useless. They can only give you answers.

Pablo Picasso

This book is about advanced input/output on the Java platform, specifically I/O using the Java 2 Standard Edition (J2SE) Software Development Kit (SDK), Version 1.4 and later. The 1.4 release of J2SE, code-named Merlin, contains significant new I/O capabilities that we’ll explore in detail. These new I/O features are primarily collected in the java.nio package (and its subpackages) and have been dubbed New I/O (NIO). In this book, you’ll see how to put these exciting new features to work to greatly improve the I/O efficiency of your Java applications.

Java has found its true home among Enterprise Applications (a slippery term if ever there was one), but until the 1.4 release of the J2SE SDK, Java has been at a disadvantage relative to natively compiled languages in the area of I/O. This weakness stems from Java’s greatest strength: Write Once, Run Anywhere. The need for the illusion of a virtual machine, the JVM, means that compromises must be made to make all JVM deployment platforms look the same when running Java bytecode. This need for commonality across operating-system platforms has resulted, to some extent, in a least-common-denominator approach.

Nowhere have these compromises been more sorely felt than in the arena of I/O. While Java possesses a rich set of I/O classes, they have until now concentrated on providing common capabilities, often at a high level of abstraction, across all operating systems. These I/O classes have primarily been stream-oriented, often invoking methods on several layers of objects to handle individual bytes or characters.

This object-oriented approach, composing behaviors by plugging I/O objects together, offers tremendous flexibility but can be a performance killer when large amounts of data must be handled. Efficiency is the goal of I/O, and efficient I/O often doesn’t map well to objects. Efficient I/O usually means that you must take the shortest path from Point A to Point B. Complexity destroys performance when doing high-volume I/O.

The traditional I/O abstractions of the Java platform have served well and are appropriate for a wide range of uses. But these classes do not scale well when moving large amounts of data, nor do they provide some common I/O functionality widely available on most operating systems today. These features — such as file locking, nonblocking I/O, readiness selection, and memory mapping — are essential for scalability and may be required to interact properly with non-Java applications, especially at the enterprise level. The classic Java I/O mechanism doesn’t model these common I/O services.

Real companies deploy real applications on real systems, not abstractions. In the real world, performance matters — it matters a lot. The computer systems that companies buy to deploy their large applications have high-performance I/O capabilities (often developed at huge expense by the system vendors), which Java has until now been unable to fully exploit. When the business need is to move a lot of data as fast as possible, the ugly-but-fast solution usually wins out over pretty-but-slow. Time is money, after all.

JDK 1.4 is the first major Java release driven primarily by the Java Community Process. The JCP (http://jcp.org/) provides a means by which users and vendors of Java products can propose and specify new features for the Java platform. The subject of this book, Java New I/O (NIO), is a direct result of one such proposal. Java Specification Request #51 (http://jcp.org/jsr/detail/51.jsp) details the need for high-speed, scalable I/O, which better leverages the I/O capabilities of the underlying operating system. The new classes comprising java.nio and its subpackages, as well as java.util.regex and changes to a few preexisting packages, are the resulting implementation of JSR 51. Refer to the JCP web site for details on how the JSR process works and the evolution of NIO from initial request to released reference implementation.

With the Merlin release, Java now has the tools to make use of these powerful operating-system I/O capabilities where available. Java no longer needs to take a backseat to any language when it comes to I/O performance.

Organization

This book is divided into six chapters, each dealing with a major aspect of Java NIO. Chapter 1 discusses general I/O concepts to set the stage for the specific discussions that follow. Chapter 2 through Chapter 4 cover the core of NIO: buffers, channels, and selectors. Following that is a discussion of the new regular expression API. Regular expression processing dovetails with I/O and was included under the umbrella of the JSR 51 feature set. To wrap up, we take a look at the new pluggable character set mapping capabilities, which are also a part of NIO and JSR 51.

For the impatient, anxious to jump ahead, here is the executive summary:

Buffers

The new Buffer classes are the linkage between regular Java classes and channels. Buffers implement fixed-size arrays of primitive data elements, wrapped inside an object with state information. They provide a rendezvous point: a Channel consumes data you place in a Buffer (write) or deposits data (read) you can then fetch from the buffer. There is also a special type of buffer that provides for memory-mapping files.

We’ll discuss buffer objects in detail in Chapter 2.

Channels

The most important new abstraction provided by NIO is the concept of a channel. A Channel object models a communication connection. The pipe may be unidirectional (in or out) or bidirectional (in and out). A channel can be thought of as the pathway between a buffer and an I/O service.

In some cases, the older classes of the java.io package can make use of channels. Where appropriate, new methods have been added to gain access to the Channel associated with a file or socket object.

Most channels can operate in nonblocking mode, which has major scalability implications, especially when used in combination with selectors.

We’ll examine channels in Chapter 3.

File locking and memory-mapped files

The new FileChannel object in the java.nio.channels package provides many new file-oriented capabilities. Two of the most interesting are file locking and the ability to memory map files.

File locking is an essential tool for coordinating access to shared data among cooperating processes.

The ability to memory map files allows you to treat file data on disk as if it was in memory. This exploits the virtual memory capabilities of the operating system to dynamically cache file content without committing memory resources to hold a copy of the file.

File locking and memory-mapped files are also discussed in Chapter 3.

Sockets

The socket channel classes provide a new method of interacting with network sockets. Socket channels can operate in nonblocking mode and can be used with selectors. As a result, many sockets can be multiplexed and managed more efficiently than with the traditional socket classes of java.net.

The three new socket channels, ServerSocketChannel, SocketChannel, and DatagramChannel, are covered in Chapter 3.

Selectors

Selectors provide the ability to do readiness selection. The Selector class provides a mechanism by which you can determine the status of one or more channels you’re interested in. Using selectors, a large number of active I/O channels can be monitored and serviced by a single thread easily and efficiently.

We’ll discuss selectors in detail in Chapter 4.

Regular expressions

The new java.util.regex package brings Perl-like regular expression processing to Java. This is a long-awaited feature, useful for a wide range of applications.

The new regular expression APIs are considered part of NIO because they were specified by JSR 51 along with the other NIO features. In many respects, it’s orthogonal to the rest of NIO but is extremely useful for file processing and many other purposes.

Chapter 5 discusses the JDK 1.4 regular expression APIs.

Character sets

The java.nio.charsets package provides new classes for mapping characters to and from byte streams. These new classes allow you to select the mapping by which characters will be translated or create your own mappings.

Issues relating to character transcoding are covered in Chapter 6.

Who Should Read This Book

This book is intended for intermediate to advanced Java programmers: those who have a good handle on the language and want (or need!) to take full advantage of the new capabilities of Java NIO for large-scale and/or sophisticated data handling. In the text, I assume that you are familiar with the standard class packages of the JDK, object-oriented techniques, inheritance, and so on. I also assume that you know the basics of how I/O works at the operating-system level, what files are, what sockets are, what virtual memory is, and so on. Chapter 1 provides a high-level review of these concepts but does not explain them in detail.

If you are still learning your way around the I/O packages of the Java platform, you may first want to take a look at Java I/O by Elliote Rusty Harold (O’Reilly) (http://www.oreilly.com/catalog/javaio/). It provides an excellent introduction to the java.io packages. While this book could be considered a follow-up to that book, it is not a continuation of it. This book concentrates on making use of the new java.nio packages to maximize I/O performance and introduces some new I/O concepts that are outside the scope of the java.io package.

We also explore character set encoding and regular expressions, which are a part of the new feature set bundled with NIO. Those programmers implementing character sets for internationalization or for specialized applications will be interested in the java.nio.charsets package discussed in Chapter 6.

And those of you who’ve switched to Java, but keep returning to Perl for the ease of regular expression handling, no longer need to stray from Java. The new java.util.regex package provides all but the most obscure regular expression capabilities from Perl 5 in the standard JDK (and adds a few new things as well).

Software and Versions

This book describes the I/O capabilities of Java, particularly the java.nio and java.util.regex packages, which first appear in J2SE, Version 1.4. Therefore, you must have a working version of the Java 1.4 (or later) SDK to use the material presented in this book. You can obtain the Java SDK from Sun by visiting their web site at http://java.sun.com/j2se/1.4/. I also refer to the J2SE SDK as the Java Development Kit (JDK) in the text. In the context of this book, they mean the same thing.

This book is based on the final JDK version, 1.4.0, released in February 2002. Early access (beta) versions of 1.4 where widely available for several months prior. Important changes were made to the NIO APIs shortly before final release. For that reason, you may see discussions of NIO published before the final release that conflict with some details in this book. This text has been updated to include all known last-minute changes and should be in agreement with the final 1.4.0 release. Later releases of J2SE may introduce further changes that conflict with this text. Refer to the documentation provided with your software distribution if there is any doubt.

This book contains many examples demonstrating how to use the APIs. All code examples and related information can be downloaded from http://www.javanio.info/. Additional examples and test code are available there. Additional code examples provided by the NIO implementation team are available at http://java.sun.com/j2se/1.4/docs/guide/nio/example/.

Conventions Used in This Book

Like all programmers, I have my religious beliefs regarding code-formatting style. The samples in this book are formatted according to my preferences, which are fairly conventional. I’m a believer in eight-column tab indents and lots of separating whitespace. Some of the code examples have had their indents reduced to four columns because of space constraints. The source code available on the web site has tab indents.

When I provide API examples and lists of methods from a class in the JDK, I generally provide only the specific methods referenced in the immediate text. I leave out the methods that are not of interest at that point. I often provide the full class API at the beginning of a chapter or section, then list subsets of the API near the specific discussions that follow.

These API samples are usually not syntactically correct; they are extracts of the method signatures without the method bodies and are intended to illustrate which methods are available and the parameters they accept. For example:

public class Foo
{
        public static final int MODE_ABC
        public static final int MODE_XYZ

        public abstract void baz (Blather blather);
        public int blah (Bar bar, Bop bop)
}

In this case, the method baz( ) is syntactically complete because abstract declarations consist of nothing but signature. But blah( ) lacks a semi-colon, which implies that the method body follows in the class definition. And when I list public fields defining constants, such as MODE_ABC and MODE_XYZ, I intentionally don’t list the values they are initialized to. That information is not important. The public name is defined so that you can use it without knowing the value of the constant.

Where possible, I extract this API information directly from the code distributed with the 1.4 JDK. When I started writing this book, the JDK was at Version 1.4 beta 2. Every effort has been made to keep the code snippets current. My apologies for any inaccuracies that may have crept in. The source code included with the JDK is the final authority.

Font Conventions

I use standard O’Reilly font conventions in this book. This is not entirely by choice. I composed the manuscript directly as XML using a pure Java GUI editor ( XXE from http://www.xmlmind.com/), which enforced the DTD I used, O’Reilly’s subset of DocBook (http://www.oasis-open.org/). As such, I never specified fonts or type styles. I’d select XML elements such as <filename> or <programlisting>, and O’Reilly’s typesetting software applied the appropriate type style.

This, of course, means nothing to you. So here’s the rundown on font conventions used in this text:

Italic is used for:

  • Pathnames, filenames, and program names

  • Internet addresses, such as domain names and URLs

  • New terms where they are defined

Constant Width is used for:

  • Names and keywords in Java code, including method names, variable names, and class names

  • Program listings and code snippets

  • Constant values

Constant Width Bold is used for:

  • Emphasis within code examples

Tip

This icon designates a note, which is an important aside to the nearby text.

Warning

This icon designates a warning relating to the nearby text.

How to Contact Us

Although this is not the first book I’ve written, it’s the first I’ve written for general publication. It’s far more difficult to write a book than to read one. And it’s really quite frightening to expound on Java-related topics because the subject matter is so extensive and changes rapidly. There are also vast numbers of very smart people who can and will point out the slightest inaccuracy you commit to print.

I would like to hear any comments you may have, positive or negative. I believe I did my homework on this project, but errors inevitably creep in. I’m especially interested in constructive feedback on the structure and content of the book. I’ve tried to structure it so that topics are presented in a sensible order and in easily absorbed chunks. I’ve also tried to cross-reference heavily so it will be useful when accessed randomly.

Offers of lucrative consulting contracts, speaking engagments, and free stuff are appreciated. Spurious flames and spam are cheerfully ignored.

You can contact me at or visit http://www.javanio.info/.

O’Reilly and I have verified the information in this book to the best of our ability, but you may find that features have changed (or even that we have made mistakes!). Please let us know about any errors you find, as well as your suggestions for future editions, by writing to:

O’Reilly & Associates, Inc.
1005 Gravenstein Highway North
Sebastopol, CA 95472
(800) 998-9938 (U.S. and Canada)
(707) 829-0515 (international/local)
(707) 829-0104 (fax)

You can also contact O’Reilly by email. To be put on the mailing list or request a catalog, send a message to:

We have a web page for this book, where we list errata, examples, and any additional information. You can access this page at:

http://www.oreilly.com/catalog/javanio/

To ask technical questions or comment on the book, send email to:

For more information about O’Reilly books, conferences, Resource Centers, and the O’Reilly Network, see O’Reilly’s web site at:

http://www.oreilly.com/

Acknowledgments

It’s a lot of work putting a book together, even one as relatively modest in scope as this. I’d like to express my gratitude to several people for their help with this endeavor.

First and foremost, I’d like to thank Mike Loukides, my editor at O’Reilly, for affording me the chance join the ranks of O’Reilly authors. I still wonder how I managed to wind up with a book deal at O’Reilly. It’s a great honor and no small responsibility. Thanks Mike, and sorry about the comma splices.

I’d also like to thank Bob Eckstein and Kyle Hart, also of O’Reilly, for their efforts on my behalf: Bob for his help with early drafts of this book and Kyle for giving me free stuff at JavaOne (oh, that marketing campaign may be helpful too). Jessamyn Read turned my clumsy pictures into professional illustrations. I’d also like to thank the prolific David Flanagan for mentioning my minuscule contribution to Java in a Nutshell, Fourth Edition (O’Reilly), and for letting me use the regular expression syntax table from that book.

Authors of technical books rely heavily on technical reviewers to detect errors and omissions. Technical review is especially important when the material is new and evolving, as was the case with NIO. The 1.4 APIs were literally a moving target when I began work on this project. I’m extremely lucky that Mark Reinhold of Sun Microsystems, Specification Lead for JSR 51 and author of much of the NIO code in JDK 1.4, agreed to be a reviewer. Mark reviewed a very early and very rough draft. He kindly set me straight on many points and provided valuable insight that helped me tremendously. Mark also took time out while trying to get the 1.4.1 release in shape to provide detailed feedback on the final draft. Thanks Mark.

Several other very smart people looked over my work and provided constructive feedback. Jason Hunter (http://www.servlets.com/) eagerly devoured the first review draft within hours and provided valuable organizational input. The meticulous John G. Miller, Jr., of Digital Gamers, Inc. (, http://www.digigamers.com/), carefully reviewed the draft and example code. John’s real-world experience with NIO on a large scale in an online, interactive game environment made this book a better one. Will Crawford (http://www.williamcrawford.info/) found time he couldn’t afford to read the entire manuscript and provided laser-like, highly targeted feedback.

I’d also like to thank Keith J. Koski and Michael Daudel (), fellow members of a merry band of Unix and Java codeslingers I’ve worked with over the last several years, known collectively as the Fatboys. The Fatboys are thinning out, getting married, moving to the suburbs, and having kids (myself included), but as long as Bill can suck gravy through a straw, the Fatboy dream lives on. Keith and Mike read several early drafts, tested code, gave suggestions, and provided encouragement. Thanks guys, you’re “phaser enriched.”

And last but not least, I want to thank my wife, Karen. She doesn’t grok this tech stuff but is wise and caring and loves me and feeds me fruit. She lights my soul and gives me reason. Together we pen the chapters in our book of life.

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