I read this in Java language Spec 17.1:
“Each object in Java is associated
with a monitor, which a thread can
lock or unlock.”
Why necessarily? Doesn’t that make java object too heavy weight? I’ve no idea why a Object like, say, a string, should be naturally a monitor!
EDIT:
I think it over and yes, Java has a keyword synchronized, because EVERY object could have a synchronized method, so it’s necessary to associate EVERY object a Monitor.
But still this seems not a very good solution, usually you need more that one mutex for one class, except for that pojo classes that’s really very simple.
Your fundamental problem is in assuming that every object has some sort of
Monitorbuilt into it, waiting for it to be used by some code. In reality, most objects are never used as a monitor, so the monitors don’t have to be created until they are used. Rather than implementing this feature as every object having aprivate Monitor monitorfield, think of it as being implemented as the JVM having a globalHashMap<object, Monitor> monitors.A possible implementation is this: Whenever a
synchronizedblock is entered, the JVM looks up the synchronized object in the map (monitors). If it finds it, it gets the monitor to use. If it doesn’t find it, it enters a critical section dedicated to the map. It then looks up the object again because another thread may have created it between the previous check and entering the critical section. If it’s still not there, it creates the monitor for the synchronized object and leaves the critical section.