Scala (18) – Concurrency with Futures in Scala

Even though we all want everything goes parallel and each task is independent with others totally, sometimes it is not simply as we think. Everything has an order, what we can do is to let independent things work at the same time, and let dependent things work by order.

A future gives us a simple way to deal with it. Each future is like an independent tasks and it starts running concurrently. But within a future, each steps in a task run by order.

Here we give two examples. one is only one task, the other is multiple tasks.

One Future

import scala.concurrent.{ Future, Await }
import scala.concurrent.duration._
val response1 = Future { create1(item) }
val returnInfo = Await.result(response1, Duration.Inf)

Multiple Futures

val response1 = Future { create1(item) }
val response2 = Future { create2(item) }
val response3 = Future { create3(item) }

val finalInfoTemp = for { 
  t <- response1
  g <- response2
  r <- response3
} yield (t, g, r)

val (t, g, r) = Await.result(finalInfoTemp, Duration.Inf)
val finalInfo = t ++ g ++ r

Note: Await.result will block the thread with a mandatory timeout duration. Blocking is not a good thing– you should block only if you really have to — but this is useful, in particular for testing purposes. blocking in general is discouraged when working with Futures and concurrency in order to avoid potential deadlocks and improve performance. Instead, use callbacks or combinators to remain in the future domain:

val finalInfoTemp: Future[Int] = for {
  a <- aFuture
  b <- bFuture
} yield a - b
finalInfoTemp.onSuccess {
  case x if x > 100 =>
}

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s