Как программист на C++, становящийся более знакомым с Java, это немного нечетно мне для наблюдения поддержки уровня языка того, чтобы соединить произвольные объекты без любого вида объявления что поддержка объектов такая блокировка. Создание взаимных исключений для каждого объекта походит на большую стоимость, которая будет автоматически выбрана в. Помимо использования памяти, взаимные исключения являются ограниченным ресурсом ОС на некоторых платформах. Вы могли вращать блокировку, если бы взаимные исключения не доступны, но рабочие характеристики этого существенно отличаются, который я ожидал бы повреждать предсказуемость.
Действительно ли JVM достаточно умна во всех случаях, чтобы распознать, что конкретный объект никогда не будет целью синхронизируемого ключевого слова и таким образом стараться не создавать взаимное исключение? Взаимные исключения могли быть созданы лениво, но это создает загружающуюся проблему, которая саму требует взаимного исключения, и даже если это работалось вокруг, я принимаю, там все еще будет немного служебными для отслеживания, было ли взаимное исключение уже создано или нет. Таким образом, я принимаю, возможна ли такая оптимизация, она должна быть сделана во время компиляции или запуск. В C++ такая оптимизация не была бы возможна из-за модели компиляции (Вы не могли знать, была ли блокировка для объекта используемой через границы библиотеки), но я не знаю достаточно о компиляции Java и соединении, чтобы знать, применяются ли те же ограничения.
Speaking as someone who has looked at the way that some JVMs implement locks ...
The normal approach is to start out with a couple of reserved bits in the object's header word. If the object is never locked, or if it is locked but there is no contention it stays that way. If and when contention occurs on a locked object, the JVM inflates the lock into a full-blown mutex data structure, and it stays that way for the lifetime of the object.
EDIT - I just noticed that the OP was talking about OS-supported mutexes. In the examples that I've looked at, the uninflated mutexes were implemented directly using CAS instructions and the like, rather than using pthread library functions, etc.
This is really an implementation detail of the JVM, and different JVMs may implement it differently. However, it is definitely not something that can be optimized at compile time, since Java links at runtime, and this it is possible for previously unknown code to get a hold of an object created in older code and start synchronizing on it.
Note that in Java lingo, the synchronization primitive is called "monitor" rather than mutex, and it is supported by special bytecode operations. There's a rather detailed explanation here.
You can never be sure that an object will never be used as a lock (consider reflection). Typically every object has a header with some bits dedicated to the lock. It is possible to implement it such that the header is only added as needed, but that gets a bit complicated and you probably need some header anyway (class (equivalent of "vtbl" and allocation size in C++), hash code and garbage collection).
Here's a wiki page on the implementation of synchronisation in the OpenJDK.
(In my opinion, adding a lock to every object was a mistake.)
can't JVM use compare-and-swap instruction directly? let's say each object has a field lockingThreadId
storing the id of the thread that is locking it,
while( compare_and_swap (obj.lockingThreadId, null, thisThreadId) != thisTheadId )
// failed, someone else got it
mark this thread as waiting on obj.
shelf this thead
//out of loop. now this thread locked the object
do the work
obj.lockingThreadId = null;
wake up threads waiting on the obj
this is a toy model, but it doesn't seem too expensive, and does no rely on OS.