memorySegment.asByteBuffer().duplicate() causes multi-MB allocations

Maurizio Cimadamore maurizio.cimadamore at oracle.com
Tue Oct 25 11:04:25 UTC 2022


Hi Sebastian.

Looking at the code, I'm having troubles to see how this could happen. I 
suppose you have a DirectBuffer on your hands. The duplicate method of 
DirectBuffer just does this:

```
public MappedByteBuffer duplicate() {
         return new DirectByteBuffer(this,
                                               this.markValue(),
                                               this.position(),
                                               this.limit(),
                                               this.capacity(),
                                               0,

                                               fileDescriptor(),
                                               isSync(),

                                               segment);
     }
```

E.g. takes a snapshot of the existing BB and return a new view with same 
characteristics. If I follow up the chain of invocations in that method, 
there's just trivial constructors, nothing which should allocate 
significant amount of memory (other than the memory to store the new BB 
view).

I think we need to take a look at a more concrete example to see what's 
going on?

Thanks
Maurizio

On 25/10/2022 07:33, Sebastian Stenzel wrote:
> Hi,
>
> using JDK 19 GA and JFR, I noticed an odd behaviour: When calling .duplicate() on a ByteBuffer, you wouldn't usually expect lots of allocations. However, when the buffer is actually a view of a MemorySegment that I retrieved from native code, I observed several hundred of MB allocations for merely a few dozens of ByteBuffers.
>
> Sadly, I don't know what the native code is doing exactly, but when I removed the `.duplicate()`, the allocations are gone. `asReadOnlyBuffer()` works fine, btw.
>
> I suspect there is some copying-to-heap taking place. Oddly enough, the observed figure of MB doesn't match the amount of data contained in those buffers. Either only a few of the buffers actually copy data or only part of the data is copied. Or the numbers are misleading for some reason I don't understand.
>
> Can anyone make sense of this?
>
> Sebastian


More information about the panama-dev mailing list