How can I convert IntBuffer to ByteBuffer without copying the data

Viewed 396

My Scala/Java code has a large (several hundred megabytes) integer arrays. I would send these as fast as possible (without copying the contents) from this int[] using java.nio. Also, when I receive any data on my nio socket channels, I would use the data as int[] without copying.

All nio operations require ByteBuffer, while ByteBuffer can only wrap byte [].

I can allocate a ByteBuffer, then put my array using asIntBuffer, but it will copy the random array and I have to store my data twice.

    val size = 1234

    val random = Array.fill[Int](size) { scala.util.Random.nextInt(1000) }

    val buf = ByteBuffer.allocate(4 * size)
    buf
      .asIntBuffer()
      .put(random)

I am using project panama openjdk, therefore any new trick (like using Pointer<>) could help me.

TL;DR: In Java or Scala, how can access my integer array as ByteBuffer and int[].

0 Answers
Related