Buffer data sources
A buffer is essentially an abstract concept. When you put data in a buffer, where
that data actually goes (and similarly, where it comes from when you read data)
depends on how the buffer has been set up.
Typically, a buffer is backed by an array or portion of an array. In other words, it "wraps"
around a Java array of a given type. Reading from and writing to the buffer will
effectively read and write to the underlying array. We'll call this array the "data source"
of the buffer. However, an array is not the only possible data source for a buffer.
Depending on how the buffer is created, the data source could be any of those listed
in Table 1 below.
|Buffer data source||How to create|
|Java byte array.||ByteBuffer.allocate() (creates a new array)|
ByteBuffer.wrap (around existing array)
|Other Java primitive array||IntBuffer.allocate()|
|"Raw" memory at arbitrary address||ByteBuffer.allocateDirect()|
|"Raw" memory at specified address||JNI function NewDirectByteBuffer()|
|Another ByteBuffer or part thereof, viewed as a ByteBuffer||bb.slice()|
|Another ByteBuffer, viewed as an IntBuffer etc||bb.asIntBuffer()|
If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants.
Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.