【问题标题】:Unable to put bytes to DirectByteBuffer in scala无法将字节放入 scala 中的 DirectByteBuffer
【发布时间】:2021-11-23 16:10:25
【问题描述】:

我最近遇到了在 Scala 代码中使用 DirectByteBuffer 的问题。下面是我的代码。

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
    }

对于整个循环,byteBuffer.remaining() 总是返回 40,这看起来像“put()”调用从来没有工作过。结果,在做“get()”时,缓冲区的内容总是0。

即使 get() 调用根本不会移动索引。

想知道为什么它没有写入 directBuffer 吗?

当使用 HeapBuffer 时,使用会产生正确的行为,而不是 DirectBuffer。

【问题讨论】:

    标签: java scala memory


    【解决方案1】:

    您的byteBuffer 被定义为def,这是一种方法:每次调用byteBuffer 时都会获得一个新缓冲区。

    您可能想将其更改为val

    【讨论】:

    • 非常感谢,我不敢相信我花了几个小时在这上面。这实际上救了我的命。
    猜你喜欢
    • 1970-01-01
    • 2018-12-11
    • 1970-01-01
    • 1970-01-01
    • 2013-10-27
    • 1970-01-01
    • 2013-03-31
    • 2016-10-26
    • 2011-12-17
    相关资源
    最近更新 更多