并行Scala批处理作业

并行Scala批处理作业,scala,concurrency,parallel-processing,Scala,Concurrency,Parallel Processing,我在Scala中有一个做批处理的函数。它被设计为自同步,因此您可以在一台机器或一个集群上运行它的1个实例或1000个实例,并且它将使用外部中间件进行同步 为了提高性能,我希望一个JVM在多个线程中运行该函数。(我希望在同一个JVM中执行此操作以节省RAM)。理想情况下,代码应该如下所示: execInParallel(9, myBatchFunction) // Starts 9 threads and invokes myBatchFunction() in each one 做这件事的简单

我在Scala中有一个做批处理的函数。它被设计为自同步,因此您可以在一台机器或一个集群上运行它的1个实例或1000个实例,并且它将使用外部中间件进行同步

为了提高性能,我希望一个JVM在多个线程中运行该函数。(我希望在同一个JVM中执行此操作以节省RAM)。理想情况下,代码应该如下所示:

execInParallel(9, myBatchFunction) // Starts 9 threads and invokes myBatchFunction() in each one

做这件事的简单方法是什么?

非阻塞版本:

import scala.concurrent._
import java.util.concurrent._
import collection.JavaConverters._

def execInParallel[T](numberThreads: Int, body: => T): util.List[Future[T]] = {
  val javaExecutor = Executors.newFixedThreadPool(numberThreads) // fixed thread pool
  val collections = Seq.fill(numberThreads) {
    new Callable[T]() {
      def call = body
    }
  }
  val futures = javaExecutor.invokeAll(collections.asJavaCollection) // run pool, first convert Seq to java.util.Collection
  // Here you have to be sure, that all task run
  import ExecutionContext.Implicits.global
  concurrent.Future(javaExecutor.shutdown()) // shutdown in new thread
  futures // return java futures !!!
}

val futures = execInParallel(9, Thread.currentThread.getName)
println("Hurray")
futures.asScala.foreach(x => println(x.get))
这可能会起作用:

 (1 to 10).toList.par.foreach(myBatchFunction)

它将调用myBatchFunction 10次,允许Scala决定何时并行执行。

代码看起来不错,但我的目标是学习,而不仅仅是获取代码。你能解释一下你做了什么以及它是如何工作的吗?检查java.util.concurrent包,或者RxJava(RxScala是包装器)-在那里你会找到你需要的所有东西。这是打字错误吗?如果“asjavacolrxscalelection”是“asJavaCollection”,这是一个java解决方案,而不是scala解决方案。Scala在jvm上运行。如果你想使用低级api,你必须使用java api。不确定它是否会创建10个线程,这可能与内核的数量有关