Reputation: 39
This was one of my interview question but I am still trying to get my head around it. If I create "new Object()", the reference to this object will be on the stack, which will be 8 bytes on 64 bit. Then, the question was what's on heap. The interviewer later mentioned that two things will always be allocated on heap, which are "Class" object as well as "Monitor". Can someone please explain a bit more about how much memory/what is allocated when "new Object()" gets created?
Upvotes: 2
Views: 1530
Reputation: 533442
If I create "new Object()", the reference to this object will be on the stack, which will be 8 bytes on 64 bit.
Most likely it with be 4 bytes even for a 64-bit JVM. Oracle/OpenJDK support CompressesOops which use 4 bytes for references.
Then, the question was what's on heap.
The object's header. It has no fields.
The interviewer later mentioned that two things will always be allocated on heap, which are "Class" object
A Class
object is a proxy for information stored off heap. It doesn't have to exist even if instances of the class exist (though for Object it probably does already)
as well as "Monitor".
Again, a monitor is only created if used i.e. synchornized
Can someone please explain a bit more about how much memory/what is allocated when "new Object()" gets created?
On a 64-bit JVM, the header is 12 bytes by default, however with object alignment, it will use 16 bytes. On a 32-bit JVM it will be just 8 bytes.
On a 32-bit JVM and a 64-bit JVM with CompressedOops, a reference is just 4 bytes (which is most JVMs)
Upvotes: 6
Reputation: 3797
Your new Object()
doesn't have a reference. Its just an object which will be allocated on the heap space.
If it were like:
Object someReference = new Object();
then someReference
would be on the stack space of thread. However the object itself will always be on the heap.
Lets take an example:
If you were to execute this statement:
Employee emp = new Employee();
You'd have memory like:
new Employee()
i.e. actual objectemp
i.e. referenceEmployee
classUpvotes: 6