如何在AnyRef上实现同步方法? [英] How is the synchronized method on AnyRef implemented?
问题描述
在Scala中,AnyRef上有一个同步方法,可让您在扩展AnyRef的任何对象上进行同步。但是,它在AnyRef上是抽象的,我无法通过greping scala源来弄清楚它是如何工作的。似乎可以通过利用Java中的synced关键字来工作。
In Scala, there's a synchronized method on AnyRef which lets you synchronize on any object that extends AnyRef. However, it's abstract on AnyRef, and I couldn't figure out how it worked from grepping the scala source. It seems like it works by exploiting the synchronized keyword in Java. Is that the case?
推荐答案
1) AnyRef.synchronized
是源代码中不存在的魔术方法,但是在每次编译器启动时都会将其注入到编译器的符号表中: Definitions.scala 。顺便说一下,有很多魔术方法和类( Definitions.scala )。
1) AnyRef.synchronized
is a magic method that doesn't exist in source code, but is injected into the compiler's symbol table on every startup of the compiler: Definitions.scala. There's a number of magic methods and classes, by the way (Definitions.scala).
2)如果方法包装在 this.synchronized $中c $ c>,删除包装,并在内部用
SYNCHRONIZED
标志( UnCurry.scala ),然后将其映射到JVM的ʻACC_SYNCHRON方法标志 GenASM.scala )。
2) If a method is wrapped in this.synchronized
, the wrapping is dropped, and the method is internally annotated with a SYNCHRONIZED
flag (UnCurry.scala), which is then mapped to JVM's `ACC_SYNCHRONIZED method access flag (GenASM.scala).
3)其他对同步的
的调用被映射到后端的原始已同步
(后端/ ScalaPrimitives) ,后来又降为monitorenter / monitorexit( GenICode.scala#1 , GenICode.scala#2 )。
3) Other calls to synchronized
are mapped onto the backend's primitive SYNCHRONIZED
(backend/ScalaPrimitives.scala), which is later lowered into monitorenter/monitorexit (GenICode.scala #1, GenICode.scala #2).
这篇关于如何在AnyRef上实现同步方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!