Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Synchronization with intrinsic locks

I'm reading B. Goetz's Java concurrency in pratice and now I'm at the section about locking. He said that

The fact that every object has a built-in lock is just a convenience so that you needn’t explicitly create lock objects.9

9 In retrospect, this design decision was probably a bad one: not only can it be confusing, but it forces JVM implementors to make tradeoffs between object size and locking performance.

Since, I'm new to concurrency it's not obvious what design decision he was talking about. Creating explicit lock object is bad from performance standpoint, isn't?

like image 318
St.Antario Avatar asked Oct 18 '22 19:10

St.Antario


1 Answers

I've never implemented a JVM myself, or even participated in its development, but I can imagine the tradeoff.

The first idea that comes to mind to associate an intrinsic lock to each object is to do just that: associate a lock, with its state (am I locked, by which thread) to each and every object created in the JVM, colocated with the rest of the object state. This should be efficient, However, it also makes each created object take additional space in memory, and that space will, most of the time, never be used (because synchronization is not that common, and most objects are never used as a lock).

Another idea would be to maintain some sort of separate lazy dictionary, that would create a lock and its state for an object only when this object is actually used as a lock. This is leass obvious, and is probably less efficient because the dictionary needs to be maintained in parallel with the objects, etc. But it would use less space in memory.

This is thus, I think, the tradeoff (or part of the tradeoff) that Brian Goetz talks about. It would indeed be less confusing, and the implementation would probably be simpler, if there were only specific objects that could act as locks.

like image 166
JB Nizet Avatar answered Nov 04 '22 01:11

JB Nizet