如何同时运行两个(从配置中获取)期货

时间:2017-08-29 17:15:20

标签: scala

我有期货清单:

val futures = List(Future(1), Future(2), Future(3), Future(4), Future(5))

我怎么能只运行两个(来自配置的值),而不是全部并行?

2 个答案:

答案 0 :(得分:4)

期货需要ExecutionContext才能运行 - 基本上是一个线程池。如果该池中只包含n个线程,那么这就是您将获得的并行度。

val pool = Executors.newFixedThreadPool(numThreads)
implicit val ec = ExecutionContext.fromExecutorService(pool)

答案 1 :(得分:0)

找到这个解决方案,我将一次只运行2个期货

def doSome(num:Int) = Future {
    num
  }

  def doSomeS(list:List[Int]): Future[List[Int]] = {
    Future.traverse(list)(doSome)
  }

  def serialiseFutures[A, B](l: List[A], size:Int)(function: List[A] ⇒ Future[List[B]])
                            (implicit ec: ExecutionContext): Future[List[B]] =
    l.grouped(size).foldLeft(Future(List.empty[B])) {
      (previousFuture: Future[List[B]], next: List[A]) =>
        for {
          previousResults: List[B] <- previousFuture
          next<- function(next)
        } yield previousResults ++ next
    }

  val list = List(1, 2, 3, 4, 5, 6, 7, 8, 9)

  serialiseFutures(list, 2)(doSomeS)