Definition of Scala Synchronized
Synchronization in general is the mechanism to control more than one thread on the same shared resource. This is the basic rule for synchronization which is applicable and true for any programming language. In scala, they provide support for threads which is based on java only. We can use java classes to implement this in scala.
Syntax:
In scala, we can synchronize a block of code by using ‘synchronized’ keyword before it. Inside this synchronized block we can write our logic that we want to synchronized. This will prevent our resource to get modified by the multiple threads at the same time hence maintain the consistency of data as well.
synchronized {
// we can write our logic here.
}
In the above piece of syntax as we can directly see we have used the keyword ‘synchronized’ to make our code synchronous. We can also see one practice example for better understanding of the syntax. See below;
synchronized {
a = b + c ; // some logic
z = a + 10;
}
How Synchronized Function Works in Scala?
As now we know that the synchronization is important when we have shared resources and we do not want multiple threads to perform operations on it at the same time so we will go for synchronization. It is important because we do not control multiple threads it will result in the data inconsistency issue for us. In Scala, we have Future trait which provides us asynchronous mechanism where multiple threads can access the same resource at the same time. This can simply be a fetching operation where data is not getting manipulated so we can use that there. Now we will have closer look at synchronous functions in scala how they work and what are their significance in detail. We will see their advantage, scenarios where we should implement them and some basic example for beginners to understand it better see below;
4.5 (5,543 ratings)
View Course
When to Use: you can use synchronization where we have shared resources and we do not want them to get modified by the multiple or various threads at the same time. This is very important where we have business logic or some calculations which are dependent on the other data also, if we do not follow this approach then the data will be inconsistent or we can also receive some errors and exceptions as well.
Let’s take one simple real time example we need synchronization without it data would be inconsistence in the database. This can be easily understanding by the bank transactions. Suppose we have a single account for two members i.e. a joint account and let’s name them as A and B. On whole, they have 2000 rupees in their account and they both want to withdraw this amount at the same time but in practice, this is not possible because only one person can get the amount. So we need to lock the resource for the same period of time when the first one ‘A’ will be done with their operations then only we will release the lock to avoid the inconsistency of data. So in this critical situation, we have to have synchronization in place to handle those scenarios well. Otherwise, Bank and customer both have to suffer and the services we are providing them will be of no use.
Example
Code:
object Main extends App{
synchronized {
println("demo for synchronized")
println("we can put the code here which we want to synchronized")
}
}
In the above example as you can see that we have created one class here Which is named as Main.scala. This class is extending the App class further. After that, we are creating one synchronized block to printing some lines of code there to understand it. So in this way, we can have our shared resource logic place there and they will acquire a look on that object until it finishes its works.
Some points need to be remembered while working with synchronization in Scala see below;
- Synchronization prevents access of multiple threads on the same object as the same time.
- In this way, this helps us preventing the data inconsistency issue for the future.
- Synchronization makes the execution of the program or process some time very slow because it allows only one thread at a time.
- During the synchronization process, it holds a lock on the resource so that no other thread can access it. All the other threads go into the waiting state until the current thread finishes its execution.
- We should try to follow the synchronization approach where we have some kind of dependency on the previous value which can impact the current value.
How to Use Synchronized in Scala?
In scala, we can make a synchronized blocks where we can place our logic. To use synchronized we need to use the synchronized’ keyword before our logic this will act as the function. Our whole logic should be cover inside this block only. So it will create a lock on the object and prevent it from being modified by another thread at the same time.
Example
Code:
synchronized {
// your logic goes here ..
}
Example of Scala Synchronized
In this example we are printing the value of integer from 1 to 10 inside the synchronized block means no other thread can access it at the same time. Simple program for beginners.
Code:
object Main extends App{
// Your code here
synchronized {
println("demo for synchronized")
println("we can put the code here which we want to synchronized")
for (i<- 0 to 10) {
println("value is ::")
println(i)
}
}
}
Output:
Conclusion
Synchronization used to avoid data inconsistence in our application. But sometimes it makes the performance a little bit slower because only a single thread operates on the object at a time. But in parallel execution, multiple threads can operate the single resource which makes the process faster but we cannot use them everywhere we need some alternative to prevent our data from being malformed.
Recommended Articles
This is a guide to Scala Synchronized. Here we also discuss the definition and how the synchronized function works in scala? along with a different example and its code implementation. You may also have a look at the following articles to learn more –