Suppose I need to process files in a given folder in parallel. In Java I would create a FolderReader thread to read file names from the folder and a pool of FileProcessor threads. FolderReader reads file names and submits the file processing function (Runnable) to the pool executor.
In Scala I see two options:
- create a pool of
FileProcessoractors and schedule a file processing function withActors.Scheduler. - create an actor for each file name while reading the file names.
Does it make sense? What is the best option?
I suggest with all my energies to keep as far as you can from the threads. Luckily we have better abstractions which take care of what’s happening below, and in your case it appears to me that you do not need to use actors (while you can) but you can use a simpler abstraction, called Futures. They are a part of Akka open source library, and I think in the future will be a part of the Scala standard library as well.
A Future[T] is simply something that will return a T in the future.
All you need to run a future, is to have an implicit ExecutionContext, which you can derive from a java executor service. Then you will be able to enjoy the elegant API and the fact that a future is a monad to transform collections into collections of futures, collect the result and so on. I suggest you to give a look to http://doc.akka.io/docs/akka/2.0.1/scala/futures.html
There’s a lot going on here:
Future.traversewhich receives as a first parameter which isM[T]<:Traversable[T]and as second parameter aT => Future[T]or if you prefer aFunction1[T,Future[T]]and returns Future[M[T]]Future.applymethod to create an anonymous class of typeFuture[T]There are many other reasons to look at Akka futures.
Futures can be mapped because they are monad, i.e. you can chain Futures execution :
Future { 3 }.map { _ * 2 }.map { _.toString }Futures have callback: future.onComplete, onSuccess, onFailure, andThen etc.
Futures support not only traverse, but also for comprehension