How exactly do Java arrays use memory in HotSpot (i.e. how many slop)?

The malloc implementation usually does not allocate the exact amount of requested memory, but instead consumes fixed amounts of memory, for example. with a capacity of two sizes, so a distribution of 1025 bytes actually occupies a 2048-byte segment with 1023 bytes lost as a slop.

Does HotSpot use a similar allocation mechanism for Java arrays? If so, what is the correct way to allocate a Java array so that there are no dips? (For example, if the length of the array should be equal to two, or possibly two, minus some fixed amount of overhead?)

+6
source share
1 answer

If you ask about the language, the answer is this: it is not specified (same as for C)

If you are asking about a specific implementation, check out this implementation. I believe that for Hotspot its dimension is 8 bytes; that is, the sizes of objects are rounded to the next granularity boundary. If the question is about increasing the size of the heap when there is not enough free heap, then it depends on the implementation, GC settings, parameters of the heap size, etc .; which makes it impossible to answer accurately.

EDIT: using a small reflexive hack, access to the class sun.misc.Unsafe (only for Oracle JRE), object references can be converted to memory addresses; print the addresses of two sequentially allocated arrays to test yourself.

And I basically asked the same question: Determine the optimal array size relative to the JVM memory granularity (Answers include an example of using the Unsafe class to check the size of an object)

+5
source

Source: https://habr.com/ru/post/988938/


All Articles