Concurrency and parallelism concepts in Scala

Category : Scala | Sub Category : Scala Interview Questions | By Prasad Bonam Last updated: 2023-09-26 23:47:14 Viewed : 274


Concurrency and parallelism are essential concepts in Scala for managing concurrent execution and improving the performance of programs, especially in multi-core processors. Here are examples illustrating concurrency and parallelism in Scala:

Concurrency:

Concurrency refers to the ability of a program to handle multiple tasks concurrently. In Scala, you can achieve concurrency using libraries like Akka and Scalas built-in Future and Promise. Here is an example using Future to perform concurrent tasks:

scala
import scala.concurrent.{Future, ExecutionContext} import scala.util.{Success, Failure} import ExecutionContext.Implicits.global def doTask1: Future[Int] = Future { Thread.sleep(1000) 42 } def doTask2: Future[Int] = Future { Thread.sleep(500) 10 } val result1: Future[Int] = doTask1 val result2: Future[Int] = doTask2 result1.onComplete { case Success(value) => println(s"Task 1 result: $value") case Failure(ex) => println(s"Task 1 failed with $ex") } result2.onComplete { case Success(value) => println(s"Task 2 result: $value") case Failure(ex) => println(s"Task 2 failed with $ex") } Thread.sleep(2000) // Wait for tasks to complete

In this example, Future is used to concurrently execute doTask1 and doTask2. The onComplete method is used to handle the results once they are available.

Parallelism:

Parallelism refers to the execution of multiple tasks simultaneously, typically on multiple cores of a processor. In Scala, you can achieve parallelism using parallel collections. Here is an example using parallel collections to perform parallel operations:

scala
val myList = (1 to 1000).toList // Sequential mapping val sequentialResult = myList.map(_ * 2) // Parallel mapping val parallelResult = myList.par.map(_ * 2) println(s"Sequential Result: $sequentialResult") println(s"Parallel Result: $parallelResult")

In this example, we have a list of numbers, and we use map to double each element. The sequential version processes elements one by one, while the parallel version processes elements concurrently on multiple cores.

Output:

yaml
Sequential Result: List(2, 4, 6, ... 2000) Parallel Result: ParVector(2, 4, 6, ... 2000)

The parallel version (myList.par.map) processes elements faster because it takes advantage of parallelism.

These examples illustrate how you can achieve concurrency and parallelism in Scala using Future for concurrent tasks and parallel collections for parallel operations. These techniques can help improve the performance and responsiveness of your Scala applications, especially in scenarios where you need to perform multiple tasks simultaneously or leverage multi-core processors.

Search
Related Articles

Leave a Comment: