简体   繁体   中英

In Java, How much memory is allocated on stack and heap for “new Object()”

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?

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 ie 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)

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:

  • Heap : stores new Employee() ie actual object
  • Stack : stores information about emp ie reference
  • Perm Space/Metaspace : stores information about Employee class

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM