Chapter 3. Channels

Brilliance! Sheer, unadulterated brilliance!

Wile E. Coyote, Super Genius

Channels are the second major innovation of java.nio. They are not an extension or enhancement, but a new, first-class Java I/O paradigm. They provide direct connections to I/O services. A Channel is a conduit that transports data efficiently between byte buffers and the entity on the other end of the channel (usually a file or socket).

A good metaphor for a channel is a pneumatic tube, the type used at drive-up bank-teller windows. Your paycheck would be the information you’re sending. The carrier would be like a buffer. You fill the buffer (place your paycheck in the carrier), “write” the buffer to the channel (drop the carrier into the tube), and the payload is carried to the I/O service (bank teller) on the other end of the channel.

The response would be the teller filling the buffer (placing your receipt in the carrier) and starting a channel transfer in the opposite direction (dropping the carrier back into the tube). The carrier arrives on your end of the channel (a filled buffer is ready for you to examine). You then flip the buffer (open the lid) and drain it (remove your receipt). You drive away and the next object (bank customer) is ready to repeat the process using the same carrier (Buffer) and tube (Channel) objects.

In most cases, channels have a one-to-one relationship with operating-system file descriptors, or file handles. Although channels are more generalized than ...

Get Java NIO now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.