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?
If one thread is executing the synchronized method, all others thread that invoke synchronized method on the same Object will have to wait until first thread is done with the Object.
First, it is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.
Can two threads call two different synchronized instance methods of an Object? No. If a object has synchronized instance methods then the Object itself is used a lock object for controlling the synchronization. Therefore all other instance methods need to wait until previous method call is completed.
You cannot call two synchronized methods of a class on the same object. This is the use of synchronization. If you can call two synchronized methods on the same object then there is a chance of corruption of the state of the object. Synchronization helps you to avoid this....
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With