Scala的期货线程池有多大?
我的Scala应用程序产生了数以百万计的future {}
s,我想知道是否可以通过配置线程池来优化它们。
谢谢。
Scala的期货线程池有多大?
我的Scala应用程序产生了数以百万计的future {}
s,我想知道是否可以通过配置线程池来优化它们。
谢谢。
The reason is that map, flatMap methods of Action allows you to call arbitrary code when joining the actions together. Slick cannot allow that code to be run on its own execution context, because it has no way to know if you are going to tie up Slicks threads for a long time.
Answers:
您可以指定自己的期货将在其中运行的ExecutionContext,而不是导入全局隐式ExecutionContext。
import java.util.concurrent.Executors
import scala.concurrent._
implicit val ec = new ExecutionContext {
val threadPool = Executors.newFixedThreadPool(1000)
def execute(runnable: Runnable) {
threadPool.submit(runnable)
}
def reportFailure(t: Throwable) {}
}
该答案来自monkjack,是已接受答案的评论。但是,您可能会错过这个好答案,因此我将其重新张贴在这里。
implicit val ec = ExecutionContext.fromExecutor(Executors.newFixedThreadPool(10))
如果只需要更改线程池数,则只需使用全局执行程序并传递以下系统属性即可。
-Dscala.concurrent.context.numThreads=8 -Dscala.concurrent.context.maxThreads=8
在Scala期货中指定线程池的最佳方法:
implicit val ec = new ExecutionContext {
val threadPool = Executors.newFixedThreadPool(conf.getInt("5"));
override def reportFailure(cause: Throwable): Unit = {};
override def execute(runnable: Runnable): Unit = threadPool.submit(runnable);
def shutdown() = threadPool.shutdown();
}
class ThreadPoolExecutionContext(val executionContext: ExecutionContext)
object ThreadPoolExecutionContext {
val executionContextProvider: ThreadPoolExecutionContext = {
try {
val executionContextExecutor: ExecutionContextExecutor = ExecutionContext.fromExecutor(Executors.newFixedThreadPool(25))
new ThreadPoolExecutionContext(executionContextExecutor)
} catch {
case exception: Exception => {
Log.error("Failed to create thread pool", exception)
throw exception
}
}
}
}