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

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Mastering Advanced Aggregations in Spark SQL
  • Thermometer Continuation in Scala
  • Deploying a Scala Play Application to Heroku: A Step-by-Step Guide
  • Upgrading Spark Pipelines Code: A Comprehensive Guide

Trending

  • Strategies for Securing E-Commerce Applications
  • Web Crawling for RAG With Crawl4AI
  • Prioritizing Cloud Security Risks: A Developer's Guide to Tackling Security Debt
  • Developers Beware: Slopsquatting and Vibe Coding Can Increase Risk of AI-Powered Attacks
  1. DZone
  2. Coding
  3. Languages
  4. How to Create Controllable Futures in Scala

How to Create Controllable Futures in Scala

In this article, we discuss how to create controllable Futures in Scala with the help of Promises.

By 
Daniel Ciocirlan user avatar
Daniel Ciocirlan
·
Apr. 21, 20 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
8.8K Views

Join the DZone community and get the full member experience.

Join For Free
This article is for the Scala programmer who has at least used or heard about Futures before. You can also find this over at the Rock the JVM blog or on YouTube in video form or embedded below:


In this article, I'm going to address the problem of "deterministic" Futures in Scala. You probably know by now that Futures are inherently non-deterministic, in the sense that if you create a Future
Scala
xxxxxxxxxx
1
 
1
val myFuture = Future {
2
    // you have no future, you are DOOMED!
3
    42
4
    // JK.
5
}

You know the value inside will be evaluated on "some" thread, at "some" point in time, without your control.

The Scenario

Here, I will speak to the following scenario which comes up often in practice. Imagine you're designing a function like this:
Scala
xxxxxxxxxx
1
 
1
def gimmeMyPreciousValue(yourArg: Int): Future[String]
2

with the assumption that you're issuing a request to some multi-threaded service which, is getting called all the time. Let's also assume that the service looks like this:
Scala
xxxxxxxxxx
1
 
1
object MyService {
2
  def produceThePreciousValue(theArg: Int): String = "The meaning of your life is " + (theArg / 42)
3
4
  def submitTask[A](actualArg: A)(function: A => Unit): Boolean = {
5
    // send the function to be evaluated on some thread, at the discretion of the scheduling logic
6
    true
7
  }
8
}

The service has two API methods:
  1. A "production" function that is completely deterministic.
  2. A submission function that has a pretty terrible API because the function argument will be evaluated on one of the service's threads, and you can't get the returned value back from another thread's call stack.
Let's assume this important service is also impossible to change, for various reasons (API breaks, etc). In other words, the "production" logic is completely fixed and deterministic. However, what's not deterministic is when the service will actually end up calling the production function. In other words, you can't implement your function as:
Scala
xxxxxxxxxx
1
 
1
def gimmeMyPreciousValue(yourArg: Int): Future[String] = Future {
2
  MyService.produceThePreciousValue(yourArg)
3
}

because spawning up the thread responsible for evaluating the production function is not up to you.

The Solution

Introducing Promises — a "controller" and "wrapper" over a Future. Here's how it works. You create a Promise, get its Future and use it (consume it) with the assumption that it will be filled in later:
Scala
xxxxxxxxxx
1
 
1
// create an empty promise
2
val myPromise = Promise[String]()
3
// extract its future
4
val myFuture = myPromise.future
5
// do your thing with the future, assuming it will be filled with a value at some point
6
val furtherProcessing = myFuture.map(_.toUpperCase())

Then pass that promise to someone else, perhaps an asynchronous service:
Scala
xxxxxxxxxx
1
 
1
val asyncCall(promise: Promise[String]): Unit = {
2
    promise.success("Your value here, your majesty")
3
}

And at the moment, the promise contains a value. Its future will automatically be fulfilled with that value, which will unlock the consumer.

How to Use it

For our service scenario, here's how we would implement our function:
Scala
x
14
 
1
def gimmeMyPreciousValue(yourArg: Int): Future[String] = {
2
    // create promise now
3
    val thePromise = Promise[String]()
4
5
    // submit a task to be evaluated later, at the discretion of the service
6
    // note: if the service is not on the same JVM, you can pass a tuple with the arg and the promise so the service has access to both
7
    MyService.submit(yourArg) { x: Int =>
8
        val preciousValue = MyService.producePreciousValue(x)
9
        thePromise.success(preciousValue)
10
    }
11
12
    // return the future now, so it can be reused by whoever's consuming it
13
    thePromise.future
14
}

We create a promise and then we return its future at the end for whoever wants to consume it. In the middle, we submit a function that will be evaluated at some point out of our control. At that moment, the service produces the value and fulfills the Promise, which will automatically fulfill the Future for the consumer.

This is how we can leverage the power of Promises to create "controllable" Futures, which we can fulfill at a moment of our choosing. The Promise class also has other methods, such as failure, trySuccess/ tryFailure and more.

I hope this was useful!
Scala (programming language)

Published at DZone with permission of Daniel Ciocirlan. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Mastering Advanced Aggregations in Spark SQL
  • Thermometer Continuation in Scala
  • Deploying a Scala Play Application to Heroku: A Step-by-Step Guide
  • Upgrading Spark Pipelines Code: A Comprehensive Guide

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!