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 sourceHow to create
Java byte array.ByteBuffer.allocate() (creates a new array)
ByteBuffer.wrap (around existing array)
Other Java primitive arrayIntBuffer.allocate()
LongBuffer.allocate()
etc
"Raw" memory at arbitrary addressByteBuffer.allocateDirect()
"Raw" memory at specified addressJNI function NewDirectByteBuffer()
Another ByteBuffer or part thereof, viewed as a ByteBufferbb.slice()
Another ByteBuffer, viewed as an IntBuffer etcbb.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.