I am trying to process some files asynchronously, with the ability to choose the number of threads the program should use. But I want to wait till processFiles() is completed processing all the files. So, I am searching for ways to stop function from returning until all the Futures are done executing. And it would be very helpful if anyone gives any ideas to approach this problem. Here is my sample code.
object FileReader{ def processFiles(files: Array[File]) = { val execService = Executors.newFixedThreadPool(5) implicit val execContext = ExecutionContext.fromExecutorService(execService) val processed = files.map { f => Future { val name = f.getAbsolutePath() val fp = Source.fromFile(name) var data = "" fp.getLines().foreach(x => { data = data ++ s"$x\n" }) fp.close() // process the data. println("Processing ....") data } } execContext.shutdown() } def main(args: Array[String]): Unit = { println("Start") val tmp = new File("/path/to/files") val files = tmp.listFiles() val result = processFiles(files) println("done processing") println("done work") } } I am thinking if my usage of Future here is wrong, please correct me if I am wrong.
My expected output :
Start Processing .... Processing .... Processing .... Processing .... Processing .... Processing .... Processing .... Processing .... Processing .... Processing .... done processing done work My current output:
Start done processing done work Processing .... Processing .... Processing .... Processing .... Processing .... Processing .... Processing .... Processing .... Processing .... Processing ....