How is the synchronized java keyword implemented?
In C#, the lock
keyword is nice syntax for a try/catch
block and an instance of Monitor
.
In Java, what synchronization class is used user the hood of the synchronized
keyword?
Edit - I did some further poking - 开发者_开发知识库looks like it synchronized gets compiled to monitorenter/monitorexit bytecode ops. Is there a class that duplicated these semantics?
No class is used - it is a language construct handled by the JVM.
However, Java 5 introduced java.util.concurrent.locks
where you have the Lock
interface and its multiple implementations. See the linked docs for sample usage.
The synchronized
keyword causes the entity it modifies to be synchronized with a lock internal to the JVM. There is no architected class for it, so far as I can recall, and it doesn't necessarily correspond to any specific OS construct.
However, there is a bytecode construct for the lock mechanism, used to enter/exit synchronized {}
blocks.
精彩评论