-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathScalaFutureExample.scala
More file actions
44 lines (36 loc) · 1.13 KB
/
ScalaFutureExample.scala
File metadata and controls
44 lines (36 loc) · 1.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package challenge2.scala_futures
import java.util.concurrent.TimeUnit
import externalLegacyCodeNotUnderOurControl.PriceService
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent._
/**
* Challenge 2: fallback in case of timeout
*
* Simple example with fixed Services - using for comprehensions.
* Created by pascal.mengelt on 29.11.2016.
*/
object ScalaFutureExample extends App {
// Starting all the services
val price1 = runService(1)
val price2 = runService(3)
val price3 = runService(1)
// collect the results
(for {
a <- price1
b <- price2
c <- price3
// calc average
} yield (a + b + c) / 3)
// print result
.foreach(price => println(s"[${Thread.currentThread().getName}] The average price is $price"))
TimeUnit.SECONDS.sleep(10)
// changed creation the Price Service
private def runService(waitFor: Int): Future[Int] =
Future.firstCompletedOf(Seq(
Future(new PriceService(waitFor).getPrice)
, Future {
TimeUnit.SECONDS.sleep(2)
println(s"[${Thread.currentThread().getName}] The special price is 42")
42
}))
}