Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why `this.synchronized` instead of just `synchronized` in Scala?

Tags:

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?

like image 918
Ivan Avatar asked Oct 19 '11 19:10

Ivan


People also ask

What is synchronized in Scala?

Scala Language synchronized synchronize on an object synchronized is a low-level concurrency construct that can help preventing multiple threads access the same resources.

Why synchronized block is better than synchronized method?

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.

Is synchronized method more efficient?

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.

Which is more preferred synchronized method or Synchronised block?

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.


1 Answers

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.

like image 83
Pablo Fernandez Avatar answered Sep 17 '22 15:09

Pablo Fernandez