In an example of working with JDBC in Scala, there is a following code:
this.synchronized { if (!driverLoaded) loadDriver() }
Why this.synchronized
instead of just synchronized
?
Scala Language synchronized synchronize on an object synchronized is a low-level concurrency construct that can help preventing multiple threads access the same resources.
synchronized block has better performance as only the critical section is locked but synchronized method has poor performance than block. synchronized block provide granular control over lock but synchronized method lock either on current object represented by this or class level lock.
If you synchronize a code block within that method then more than one thread can execute the method simultaneously, but only one thread can enter the synchronized block at a time. From this we can conclude that synchronizing on the smallest possible code block required is the most efficient way to do it.
In other words, the synchronized method increases the waiting time, whereas synchronized block has an advantage over the method as its scope is limited and smaller than the method.
In scala synchronized
is not a keyword, as in java.
It is in fact a member of AnyRef
, which is scala equivalent for java's Object
.
So to answer your question, you can either use synchronized
or this.synchronized
, just as you can do toString
or this.toString
.
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