How is the synchronized method on AnyRef implemented?

后端 未结 2 907
[愿得一人]
[愿得一人] 2021-01-11 09:57

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 o

2条回答
  •  情深已故
    2021-01-11 10:08

    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) 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) 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).

提交回复
热议问题