Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objects allocated on heap

Whenever any new object is created, the object is created on heap. The memory allocated for each object has two additional fields 1) The type object pointer 2) sync block index.

What exactly is the usage of these two fields. Can anybody shed light on this?

like image 937
Justin Samuel Avatar asked Oct 27 '09 06:10

Justin Samuel


People also ask

Are objects allocated on the heap?

In Java, all objects are dynamically allocated on Heap. This is different from C++ where objects can be allocated memory either on Stack or on Heap. In JAVA , when we allocate the object using new(), the object is allocated on Heap, otherwise on Stack if not global or static.

Are objects allocated on the heap or stack?

Whenever an object is created, it's always stored in the Heap space and stack memory contains the reference to it. Stack memory only contains local primitive variables and reference variables to objects in heap space.

What gets allocated on the heap?

Heap Allocation: The memory is allocated during the execution of instructions written by programmers.

Why are objects stored in heap memory?

Heap space is used for the dynamic memory allocation of Java objects and JRE classes at runtime. New objects are always created in heap space, and the references to these objects are stored in stack memory. These objects have global access and we can access them from anywhere in the application.


2 Answers

The type object pointer is used to represent the type of the object. This is required for:

  • Method lookup (the vtable)
  • Checking casts
  • Finding the Type object if you call GetType.

The syncblock field is primarily used for locking. It's only filled in when it needs to be, and when a lock is always uncontested the CLR makes do with a "thin" lock which doesn't require any external data. Otherwise, it's an entry in a process-wide table - I don't know the details of what's in the table, but I would imagine it's things like a list of threads waiting on the object's monitor. Of course the most important bit of information is whether or not the lock is currently held, by which thread, and what its count is (due to the reentrant nature of .NET locks).

The syncblock is also filled in if you call GetHashCode() and it's not overridden - it uses the process-wide table to allocate a stable number, basically. (The address of the object isn't good enough as it can change over time.)

like image 171
Jon Skeet Avatar answered Sep 29 '22 03:09

Jon Skeet


Type object is what returned by obj.GetType call

sync block used for synchronization

See:

  • CLR Memory Model Part 1
  • CLR Memory Model Part 2
  • More on locks
like image 26
Ilya Khaprov Avatar answered Sep 29 '22 03:09

Ilya Khaprov