Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is the synchronized method on AnyRef implemented?

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?

like image 981
nnythm Avatar asked Jul 13 '13 04:07

nnythm


People also ask

What will happen if a synchronized method is called?

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.

Can two threads access two different synchronized methods on an 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.

What will happen if a synchronized method is called by two threads on different?

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.

Can two static synchronized methods be called by two threads using the same diff object?

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 Answers

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

like image 158
Eugene Burmako Avatar answered Sep 28 '22 03:09

Eugene Burmako