Why does the future have a maximum of 4 concurrent threads? The number of threads in a thread pool is determined by ExecutionContext. If you are using the default global, there are only 4 concurrent threads. Import Scala.concurrent.ExecutionContext.Implicits.global
where does the default global ExecutionContext set 4 concurrent threads? Global uses Executioncontextimpl, which has a code like this:
def createExecutorService: ExecutorService = {
def GetInt ( name : string , f Span class= "pun" >: string => int ): int =
/span>try f ( system getproperty ( name catch { Span class= "PLN" > case e : exception => Span class= "PLN" > runtime getruntime availableprocessors
def range(floor: Int, desired: Int, ceiling: Int): Int =
if (Ceiling< Floor)Range(Ceiling,desired, Floor) ElseScala.Math.min(Scala.Math.Max(desired, Floor),Ceiling)
val desiredParallelism = range(
getInt("scala.concurrent.context.minThreads", _.toInt),
getInt("scala.concurrent.context.numThreads", {
case null | "" => Runtime.getRuntime.availableProcessors
Casesifs.charAt(0) == ' x ' = (Runtime.GetRuntime.availableprocessors*s.substring(1).todouble).Ceil.ToInt
case other => other.toInt
}),
getInt("scala.concurrent.context.maxThreads", _.toInt))
val threadFactory = new DefaultThreadFactory(daemonic = true)
try {
new ForkJoinPool(
desiredParallelism,
threadFactory,
uncaughtExceptionHandler,
true) // Async all the way baby
} catch {
MakersForkjoinpoolwhen you set thedesiredparallelism. You can see how much parallelism the Desiredparallelism function is based on system variables (note the Getint function):scala.concurrent.context.minThreads:minimum number of concurrent threads (INT)
scala.concurrent.context.numThreads:the number of concurrent threads, and if it is int, this value is used, and if it is a string and starts with "X" followed by a double (such as "x1.5"), its value is 1.5 *Runtime.getRuntime.availableProcessors
scala.concurrent.context.maxThreads:Maximum number of concurrent threads(INT)
If these three variables are not set, Getint will take Runtime.getRuntime.availableProcessors, which is the current CPU's number of cores. So there are only 4 concurrent threads running the future on my computer.
How do I change the number of concurrent threads for the future? 1. From the above code analysis it is easy to think that if you are still using global executioncontext, you can modify the system variables:
System.setProperty("scala.concurrent.context.minThreads", "8")
System.setProperty("scala.concurrent.context.maxThreads", "8")
2. A better approach is to rewrite one's own 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) {}
}
From for notes (Wiz)
The number of future threads in Scala