DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Thermometer Continuation in Scala
  • Deploying a Scala Play Application to Heroku: A Step-by-Step Guide
  • Upgrading Spark Pipelines Code: A Comprehensive Guide
  • Java vs. Scala: Comparative Analysis for Backend Development in Fintech

Trending

  • Microsoft Azure Synapse Analytics: Scaling Hurdles and Limitations
  • AI Meets Vector Databases: Redefining Data Retrieval in the Age of Intelligence
  • Recurrent Workflows With Cloud Native Dapr Jobs
  • A Guide to Container Runtimes
  1. DZone
  2. Coding
  3. Languages
  4. Scala Futures: Concurrency Interpreted!

Scala Futures: Concurrency Interpreted!

Futures let us run values off the main thread and handle background or yet to be run values by mapping them with callbacks. See how they work in Scala.

By 
Jay Reddy user avatar
Jay Reddy
·
Updated Jan. 04, 21 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
8.4K Views

Join the DZone community and get the full member experience.

Join For Free

Futures allow us to run values off the main thread and handle values that are running in the background or yet to be executed by mapping them with callbacks.

If you come from a Java background, you might be aware of java.util.concurrent.Future. There are several challenges in using this:

  1. Threads are always blocked while retrieving values.
  2. The wait time for the completion of computation.
  3. The GET method is the only way to retrieve values.

It’s a weary and antagonistic way of writing concurrent code.

We have better Futures in Scala with Scala.concurrent.Future. With Scala Futures, we can achieve:

  1. Real-time non-blocking computations.
  2. Callbacks for onComplete (success/failure), i.e., values in Future are instances of the Try clause.
  3. The mapping of multiple Futures.

Futures are immutable by nature and are cached internally. Once a value or exception is assigned, Futures cannot be modified/overwritten (it’s hard to achieve referential transparency).

Simple example:

Scala
 




x
16


 
1
import scala.concurrent.{Future}
2
import scala.concurrent.ExecutionContext.Implicits.global
3
import scala.util.{Failure, Success}
4

           
5
object ScalaFuture extends App {
6
  def findingFrancis = {
7
    println("where is your boss? you only got 1 second ,you are about to be killed by Scala compiler")
8
    Thread.sleep(1000)
9
    println("Finding Francis...")
10
  }  //  Add your logic
11

           
12
  val whereIsFrancis = Future {
13
    findingFrancis
14
    //    wait time until the login executes, returns nothing if the code is compiled soon by compiler that then future is executed
15
  }
16
}



ExecutionContext

Think of ExecutionContext as an administrator who allocates new threads or uses a pooled/current thread (not recommended) to execute Futures and their functions. Without importing ExecutionContext into scope, we cannot execute a future.

Scala
 




xxxxxxxxxx
1


 
1
import scala.concurrent.ExecutionContext.Implicits.global



Global ExecutionContext is used in many situations to dodge the need to create a custom ExecutionContext. The default global ExecutionContext will set the parallelism level to the number of available processors (can be increased).

Callbacks

Futures eventually return values that needs to be handled by callbacks.
Unhandled values/exceptions will be lost.

Futures have methods that you can use. Common callback methods are:

  • onComplete callback values in Future are instances of the Try clause:
Scala
 




xxxxxxxxxx
1


 
1
def onComplete[U](f: Try[T] => U)(implicit executor: ExecutionContext): Unit



onSuccess and onFailure are deprecated. You can use filter, foreach, map, and many more — learn more here.

Scala
 




xxxxxxxxxx
1


 
1
whereIsFrancis.onComplete {
2
    case Success(foundFrancis) => println(s"heads up dummy $foundFrancis")
3
    case Failure(exception) => println(s"F***** unreal $exception")
4
  }



Await

This approach is used only in system where blocking a thread is necessary. It’s not usually recommended because it impacts performance.

Await.result will block the main thread and waits for the specified duration for the result.

Scala
 




xxxxxxxxxx
1


 
1
def result[T](awaitable: Awaitable[T], atMost: Duration): T



The above code will only display:

Image for post
Scala
 




xxxxxxxxxx
1


 
1
whereIsFrancis.onComplete {
2
    case Success(foundFrancis) => println(s" found you, heads up dummy $foundFrancis")
3
    case Failure(exception) => println(s"F***** unreal $exception")
4
  }
5
Await.result(whereIsFrancis,2.seconds)



This requires Duration import for seconds. To handle time in concurrent applications, Scala has:

Scala
 




xxxxxxxxxx
1


 
1
import scala.concurrent.duration._



This support different time units:
toNanos, toMicros, toMillis, toSeconds, toMinutes, toHours, toDays, and toUnit(unit: TimeUnit).

For bulky code, callbacks are not always the best approach. Scala futures can be used with for (enumerators) yield e, where enumerators refers to a semicolon-separated list. An enumerator is either a generator which introduces new variables or it is a filter.

Scala
 




xxxxxxxxxx
1


 
1
val result: Future[(String, String, String)] = for {
2
    Cable    <- fromFuture
3
    DeadPool <- notFromFuture
4
    Colossus <- notFromFuture
5
} yield (Cable, DeadPool, Colossus)



Good to Know

Exceptions

When asynchronous computations throw unhandled exceptions, Futures associated with those computations fail. Failed futures store an instance of Throwable instead of the result value. Future provides the failed projection method, which allows the Throwable to be treated as the success value of another Future. 

Projections

To allow us to understand a result returned as an exception, Futures also have projections. If the original Future fails, the failed projection returns a future containing a value of type Throwable. If the original Future succeeds, the failed projection fails with a NoSuchElementException. 

Complete Code

Scala
 




xxxxxxxxxx
1
20


 
1
import scala.concurrent.{Future}
2
import scala.concurrent.ExecutionContext.Implicits.global
3
import scala.util.{Failure, Success}
4
import scala.concurrent.duration._object ScalaFuture extends App {
5
  def findingFrancis = {
6
    println("where is your boss? you only got 1 second ,you are about to be killed by scala compiler")
7
    Thread.sleep(1000)
8
    println("Finding Francis...")
9
  }  //  Add your logic
10

           
11
  val whereIsFrancis = Future {
12
    findingFrancis
13
    //    wait time until the login executes
14
  }
15
    whereIsFrancis.onComplete {
16
      case Success(foundFrancis) => println(s" found you, heads up dummy $foundFrancis")
17
      case Failure(exception) => println(s"****** unreal $exception")
18
    }
19
  Await.result(whereIsFrancis, 2.seconds)
20
}



Output

After making the main thread wait two seconds, we get to see the output from the Future thread as below:Image for post

Conclusion

Futures are a great approach to run parallel programs in an efficient and non-blocking way. We can achieve this in a more functional way using external libraries (scalaz, cats, etc.).

Akka is an actor model library built on Scala and provides a way to implement long-running parallel processes (to overcome limitations of Scala Futures). Futures are used in other frameworks that are built using Scala like Play Framework, lagom, Apache Spark, etc.

Check out our page YolkOrbit for more on Scala and Akka.

Thanks for reading and the support.

Scala (programming language)

Published at DZone with permission of Jay Reddy. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Thermometer Continuation in Scala
  • Deploying a Scala Play Application to Heroku: A Step-by-Step Guide
  • Upgrading Spark Pipelines Code: A Comprehensive Guide
  • Java vs. Scala: Comparative Analysis for Backend Development in Fintech

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!