Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where array of primitives stored in JVM memory

Tags:

java

memory

jvm

JVM memory is divided into: 1. Method Area 2. Heap Area 3. Stack 4. PC Register 5. Native Stack

  1. Now suppose I have a class having property of say "int[] dealCodes"(array of int primitive). As per memory management once deal code is initialized, there would be contiguous memory allocation of (total_elements * 4 bytes) in memory. So if array size is 10 then there will be 40 bytes allocation in JVM memory.

    My question is in which area this 40 bytes will be allocated (heap or stack)?

    My understanding about array is: it's just like any other object and resides under heap area but don't know about primitives to which array points to.

  2. Also want to know about similar scenario when array holds references (e.g. array of type Employees). I think in this case, everything will be in heap area. As these are references then array will hold 4 bytes for each reference (32 bit system) and these references will point to objects of varying size. Array memory allocation will be calculated on basis of reference size not object size.

Please help me to get clarity on above 2 points.

like image 204
Shashi Shankar Avatar asked Sep 29 '22 08:09

Shashi Shankar


1 Answers

Objects are always Heap allocated so your dealCodes will be allocated there only but the total memory allocated is more than 40 bytes.

12 bytes (Header) + 4 bytes (Length of Array) + 40 bytes (4 bytes * 10 ints) = 56 bytes

Same thing applies to an array of Employee objects as well except that each array element is now a reference to Employee object, so the Shallow Heap occupied by employees array is still 56 bytes while the Retained Heap depends on the size of each Employee object.

You can use VisualVM in JDK_HOME/bin directory to take a snapshot of your program/application, see the memory occupied by each object, both shallow and retained heap sizes.

like image 158
Arkantos Avatar answered Oct 05 '22 21:10

Arkantos