Java Reference
In-Depth Information
output . compact ();
}
} catch ( IOException ex ) {
key . cancel ();
try {
key . channel (). close ();
} catch ( IOException cex ) {}
}
}
}
}
}
One thing I noticed while writing and debugging this program: the buffer size makes a
big difference, although perhaps not in the way you might think. A big buffer can hide
a lot of bugs. If the buffer is large enough to hold complete test cases without being
flipped or drained, it's very easy to not notice that the buffer isn't being flipped or com‐
pacted at the right times because the test cases never actually need to do that. Before
shipping your program, try turning the buffer size down to something significantly
lower than the input you're expecting. In this case, I tested with a buffer size of 10. This
test degrades performance, so you shouldn't ship with such a ridiculously small buffer,
but you absolutely should test your code with small buffers to make sure it behaves
properly when the buffer fills up.
Duplicating Buffers
It's often desirable to make a copy of a buffer to deliver the same information to two or
more channels. The duplicate() methods in each of the six typed buffer classes do this:
public abstract ByteBuffer duplicate ()
public abstract IntBuffer duplicate ()
public abstract ShortBuffer duplicate ()
public abstract FloatBuffer duplicate ()
public abstract CharBuffer duplicate ()
public abstract DoubleBuffer duplicate ()
The return values are not clones. The duplicated buffers share the same data, including
the same backing array if the buffer is indirect. Changes to the data in one buffer are
reflected in the other buffer. Thus, you should mostly use this method when you're only
going to read from the buffers. Otherwise, it can be tricky to keep track of where the
data is being modified.
The original and duplicated buffers do have independent marks, limits, and positions
even though they share the same data. One buffer can be ahead of or behind the other
buffer.
Duplication is useful when you want to transmit the same data over multiple channels,
roughly in parallel. You can make duplicates of the main buffer for each channel and
Search WWH ::




Custom Search