I recently encountered an issue using DirectByteBuffer in scala code. Below is my code.
def byteBuffer = ByteBuffer.allocateDirect(10 * 4)
for (i <- 0 until 10) {
println(s"Remaining: ${byteBuffer.remaining()}") // Always return 40
byteBuffer.putFloat(1) // Also tried byteBuffer.putFloat(i, 1) to try to put it to specific index, still nothing changed.
}
byteBuffer.position(0) // With or without this line, result doesn't change
for (i <- 0 until 40) {
println(s"At index=$i, get=${byteBuffer.get()}") // Always 0
println(byteBuffer.remaining()) // Always 40
}
For the entire loop, byteBuffer.remaining() always returns 40, which seem like the "put()" calls never worked. As a result, the content when doing "get()", content of the buffer is always 0.
Even get() call does not move the index at all.
Was wondering the reason why it is not writing to the directBuffer?
When using HeapBuffer, the usage would generate the correct behavior, just not DirectBuffer.
CodePudding user response:
Your byteBuffer
is defined as a def
, that's a method: each time you call byteBuffer
you get a new buffer.
You probably want to change it to a val
?