Search code examples
javaoptimizationmemory-managementjvmjavac

Java Object[] and cache strading


As we know when memory is moved to L caches on cpu it is moved with cachelines, thus the whole cache strading performance optimization...

Well in java when we define an array jmm guarantees that memory for each element will be allocated sequentially. However if we have array of references, those references can point randomly to different places in the memory.

My question is does java allocate actual objects memory sequentially? What optimizations do we have under the hood for this?

For example if we declare int[] we are confident those are all actually sequential in memory, but if we define a NewType (like struct) that has two int fields in it, and declare NewType[] will java figure out and keep actual memory sequentially or not?


Solution

  • My question is does java allocate actual objects memory sequentially?

    This is not guaranteed, but most of the time the OpenJDK/Oracle JVM does. Some of the times it doesn't are;

    • when you allocate a large object in tenured space,
    • your TLAB is full and you need to get another one.

    However, within the TLAB, it just allocates sequentially in memory.

    declare NewType[] will java figure out and keep actual memory sequentially or not?

    Java doesn't figure out anything, nor does it go out of it's way to allocate objects randomly in memory. In general, each new object will be immediately after the last one.