Reputation: 39
I am new to Scala and I'm trying to get an handle on futures and multithreading
I have a SingleThreaded version of a program that makes some calculations on a matrix
SingleThreadCalc {
def run(matrix : Seq[Seq[Double]]) : Future[Seq[Seq[Double]] = Future{doMath(matrix)}
}
What i want now is to make a multithreaded version of it. is it enought to just pass an ExecutionContext with a number of threads?
MultiThreadCalc {
def run(matrix : Seq[Seq[Double]]) : Future[Seq[Seq[Double]] =
Future{doMath(matrix)} (ExecutionContext.fromExecutor(Executors.newFixedThreadPool(10)))
Will this share the computation load between all the threads or is it not happening at all?
Upvotes: 0
Views: 955
Reputation: 26579
Short answer: No.
Long answer:
object MultiThreadCalc {
def run(matrix : Seq[Seq[Double]]) : Future[Seq[Seq[Double]] =
Future{doMath(matrix)}(ExecutionContext.fromExecutor(Executors.newFixedThreadPool(10)))
}
The code above will, for every invocation of run
, will allocate a new thread pool which will never be shut down, and it will be used to execute a single method doMath
(so only 1 thread in that pool will be used).
Now, if you want to parallelize execution of doMath
itself, then you'll need to modify ts definition to be parallelizable, possibly by making it take an implicit ec: ExecutionContext
parameter and using that within its definition.
But if you instead want to be able to run many invocations of doMath
in parallel then you can do the following:
object MultiThreadCalc {
def run(matrix : Seq[Seq[Double]])(implicit ec: ExecutionContext) : Future[Seq[Seq[Double]] = Future{doMath(matrix)}
}
And then create an ExecutionContext possibly ExecutionContext.fromExecutor(Executors.newFixedThreadPool(10))
on the "outside" and use it whenever you want to execute logic on it.
Upvotes: 1