When the 'new' opcode is called in the JVM, it allocates memory for the new object but does not call the constructor. The size of the allocated memory is fixed based on the class definition and architecture of the JVM. For an object, the memory consists of a header plus contiguous space for each instance field, with primitive types and arrays taking up predefined sizes.
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
What happens when 'new' is called in the JVM (2/2
1. 'new' in JVM (2/2)
What happen when 'new' is called?
Kengo TODA 2012/May/30
2. Summary for previous
Opcode ‘new’ doesn’t call constructor.
Data size is fixed at first (by opcode ‘new’).
JVM can decide size from class definition.
How?
4. the IBM says...
In the IBM JVM, each data has
2 parts:
Headers
size+flags, mptr, locknflags
Object data
↑ quoted from dW
5. about headers
Each instance has headers. It means:
each instance eats 16 bytes in 32bit JVM
each instance eats 24 bytes in 64bit JVM
Object size is decided according to JVM
architecture.
6. about Object data
Object data = set of instance fields
This data eats contiguous space on memory
Object data of class with 3 fields
char byte int
7. about Object data
Object data = set of instance fields
boolean and byte eat 1 byte
char and short eat 2 bytes
int and float eat 4 bytes
long and double eat 8 bytes
8. about Object data
special cases:
array: eats (length * element size) bytes
reference:
4 bytes on 32bit JVM
8 bytes on 64bit JVM
9. example
class which has 2 ‘int’s on 64bit JVM
24 bytes + 4 * 2 bytes = 32 bytes
class which has ‘byte[16]’ on 64bit JVM
24 bytes + 1 * 16 bytes = 40 bytes
10. example (corner case)
class which has 2 reference on 64bit JVM
24 bytes + 8 * 2 bytes = 40 bytes
24 bytes + 4 * 2 bytes = 32 bytes if
Ordinary Object Pointer is enabled
11. example (corner case)
class which has 1 ‘int’s on 64bit JVM
24 bytes + 4 bytes -> 32 bytes ≒ 24 + 4
because JVM uses 8 bytes memory block
12. key point
Object size = size of header + Σ (field).
Array requires contiguous space to store.
13. References
The Java™ Virtual Machine Specification
Sensible Sanitation -- Understanding the IBM
Java Garbage Collector
From Java code to Java heap