EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

Scala Synchronized

By Shalu SharmaShalu Sharma

Home » Software Development » Software Development Tutorials » Scala Tutorial » Scala Synchronized

Scala Synchronized

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:

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

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;

Popular Course in this category
Scala Programming Training (3 Courses,1Project)3 Online Courses | 9+ Hours | Verifiable Certificate of Completion | Lifetime Validity | 1 Project
4.5 (5,543 ratings)
Course Price

View Course

Related Courses
Programming Languages Training (41 Courses, 13+ Projects, 4 Quizzes)All in One Software Development Bundle (600+ Courses, 50+ projects)

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:

Scala Synchronized-1.1

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 –

  1. Scala Finds
  2. Firebase vs MongoDB
  3. Scala Implicit
  4. Scala IDE

Scala Programming Training (3 Courses,1Project)

3 Online Courses

9+ Hours

Verifiable Certificate of Completion

Lifetime Validity

1 Project

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
Scala Tutorial
  • Advanced
    • Constructors in Scala
    • Scala Class Constructor
    • Scala Abstract Class
    • Scala String
    • Scala Collections
    • Scala High Order Functions
    • Scala Date Function
    • Scala Stream
    • Scala Class
    • Scala Function
    • Scala Closure
    • Scala Range
    • Scala Either
    • Scala Random
    • Scala Tuples
    • Scala Partial Function
    • Scala Split
    • Scala Finds
    • Scala List
    • Scala Trait
    • Scala Try Catch
    • Scala Regex
    • Scala Vector
    • Scala Seq
    • Scala Byte
    • Scala ListBuffer
    • Scala ArrayBuffer
    • Scala flatMap
    • Scala HashMap
    • Scala Map Function
    • Scala SortBy
    • Scala Some
    • Scala Generic
    • Scala getOrElse
    • Scala REPL
    • Scala Logging
    • Scala Lambda
    • Scala Queue
    • Scala Set
    • Scala Singleton
    • Scala groupBy
    • Scala reduce
    • Scala filter
    • Scala Option
    • Scala Native
    • Scala DataFrame
    • Scala Anonymous Function
    • Scala Read File
    • Scala Write to File
    • Scala Pattern Matching
    • Scala ClassTag
    • Scala Synchronized
    • Scala zipwithindex
    • Scala Interview Questions
  • Basics
    • What is Scala?
    • Uses of Scala
    • Scala Versions
    • Scala Data Types
    • Scala Companion Object
    • Scala Operators
    • Scala: The Functional Approach
    • Scala Object
    • Scala Implicit
    • Scala IDE
  • Control Flow
    • Scala if else
    • Break in Scala
    • Scala for Loop
    • Scala foreach
    • Scala While Loops

Related Courses

Scala Programming Training Course

Programming Language Course

Software Development Course Training

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - Scala Programming Training (3 Courses,1Project) Learn More