简体   繁体   English

同步的 java 关键字是如何实现的?

[英]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 .在 C# 中, lock关键字是try/catch块和Monitor实例的好语法。

In Java, what synchronization class is used user the hood of the synchronized keyword?在 Java 中,用户使用synchronized关键字的引擎盖是什么同步 class?

Edit - I did some further poking - looks like it synchronized gets compiled to monitorenter/monitorexit bytecode ops.编辑 - 我做了一些进一步的戳 - 看起来它同步被编译为 monitorenter/monitorexit 字节码操作。 Is there a class that duplicated these semantics?是否有重复这些语义的 class ?

No class is used - it is a language construct handled by the JVM.不使用 class - 它是由 JVM 处理的语言结构。

However, Java 5 introduced java.util.concurrent.locks where you have the Lock interface and its multiple implementations.但是,Java 5 引入了java.util.concurrent.locks ,其中您有Lock接口及其多个实现。 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. synchronized关键字导致它修改的实体与 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.据我所知,它没有架构的 class ,它不一定对应于任何特定的操作系统构造。

However, there is a bytecode construct for the lock mechanism, used to enter/exit synchronized {} blocks.但是,锁机制有一个字节码结构,用于进入/退出同步的{}块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM