Twitter Future in scala

Reading Time: 2 minutes

When we want a simple way to run one or more tasks concurrently in a Scala application. Including a way to handle their results when the tasks finish then we use the scala future. In this blog, we are going to discuss Twitter Future. Twitter futures are more explicit about where computations are executed than the Scala standard library futures. This approach has several advantages over the standard library’s future API. For one thing, it keeps method signatures simpler, since there’s not an implicit ExecutionContext that has to be passed around everywhere. Some method names are different and Twitter Future has some new helper methods in the companion.

Finagle uses futures  to encapsulate and compose concurrent operations such as network RPCs. Futures are directly analogous to threads  they provide independent and overlapping threads of control 

I would tell the main difference that could go in favor of using Twitter Future is that it can be canceled, unlike scala’s Future. It can be useful to cancel asynchronous work to free up the resources, even though the thread itself is not blocked. Scala doesn’t implement cancellation. Twitter futures allow users to set interrupt handlers and can propagate interruptions up the flatMap chain so that if a future is no longer needed, it can cancel.

Future Pool 

FuturePool manages a pool of threads that don’t do any other work. It means that blocking operations won’t halt other asynchronous work. There are default implementations that can wrap a java.util.concurrent.ExecutorService as well as a FuturePool.unboundedPool for executing I/O. Note that as the name implies, unboundedPool, is unbounded and you must take care to not enqueue work faster than you can complete the tasks or you will have a memory leak. You can create a bounded FuturePool via FuturePool.apply(ExecutorService).

In the following example, I have used the unbounded future pool that internally uses newCachedThreadPool.

To use twitter future in scala Following is the library dependency required to use in build.sbt.

libraryDependencies += "com.twitter" %% "util-core" % "19.12.0"

 Let’s see an example of how to use twitter future in scala.

object TwitterFutureExample extends App{

    val unboundedPool = FuturePool.unboundedPool
    println("1 - starting calculation ...")
    def getValue =  42
   
    def increment(number: Int)=number+1

    val incrementByGettingValue = unboundedPool {
      increment(getValue)
    }

    println("2- before onSuccess")
    incrementByGettingValue.onSuccess{
      case value => println("Got the callback "+value)
    }
    println("A ...")
    println("B ...")
    println("C ...")
}

After running the above code you will get the following output.

1 - starting calculation ...
2- before onSuccess
Got the callback 43
A ...
B ...
C ...

If we want to use the value which is computed by the future then we need to resolve the future to a final value. If you want to get the value in scala future we use Await.result which blocks the main thread until the future completes the computation of the future. Twitter future provides a method poll. The core method of future, poll, attempts to resolve the future into a final value. This method does not block if the value is not ready. Instead, the current task is scheduled to be woken up when it’s possible to make further progress by polling again. The context passed to the poll method can provide a Waker, which is a handle for waking up the current task.

Just add one line in the above code.

println(incrementByGettingValue.poll)

This will give you the following result 

Some(Return(43))

References-

http://1.https://twitter.github.io/finagle/guide/developers/Futures.html

http://2.https://twitter.github.io/util/guide/util-cookbook/futures.html

Leave a Reply