Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET: why store Sync Block in every object?

In .NET, why is lock(someObject) implemented the way it is? The way I see it, there were two options to store synchronization info:

  1. Global hashtable to map memory address -> synchronization info
  2. Store pointer or index to synchronization info inside every object that could possibly be locked.

In the first implementation, there is no memory overhead for objects that are not locked - they do not get any hashtable entries. However, .NET uses the second implementation, storing a Sync Block Index field in the header of every single .NET object - even those that are never locked.

What is the motivation behind this choice? What scenarios is this optimized for?

like image 979
Sergei Patiakin Avatar asked Oct 31 '16 16:10

Sergei Patiakin


1 Answers

The CLR has one header word for the synchronization info and other things such as the object identity hash code. It's a multi-purpose field.

But still, your argument is valid: This could be implemented using a global hash table. This would decrease memory and object creation cost for most objects and increase locking and identity hash code costs. I could see this making sense but it's workload dependent.

Also, from the linked article it looks like COM and MarshalByRefObject information is stored there as well. Maybe this forces this data to be included in the object header for performance reasons. For example, each method call on a MarshalByRefObject has some overhead to check for remoted objects. Maybe someone with actual knowledge can comment/answer on this idea.

More subjectively, I think being able to lock every object is bad design in the first place. Likely, this was only kept for Java compatibility. The whole MarshalByRefObject idea is a total design failure as well. (COM interop is OK.)

like image 116
usr Avatar answered Oct 21 '22 19:10

usr