Posted By

tedg on 11/26/13


Tagged

Asynchronous


Versions (?)

A Simple and Complete Scala Concurrent Program Using Future with Work Done Asynchronously


 / Published in: Scala
 

A Simple and Complete Scala Concurrent Program Using Future with Work Done Asynchronously

  1. import scala.concurrent.{Future, future, Await}
  2. import scala.concurrent.ExecutionContext.Implicits.global
  3. import scala.concurrent.duration.Duration
  4.  
  5. /**
  6.  * This program expects a text file containing the word "computation"
  7.  * in the directory C:\tmp. The file name is expected to be "myText.txt"
  8.  */
  9. object FutureTest extends App {
  10. val firstOccurrence: Future[Int] = future {
  11. val source = scala.io.Source.fromFile("C:\\tmp\\myText.txt")
  12. source.toSeq.indexOfSlice("computation")
  13. }
  14.  
  15. firstOccurrence.onSuccess {case n =>
  16. println(n);
  17. }
  18.  
  19. firstOccurrence.onFailure {case t =>
  20. println(t.getMessage())
  21. }
  22.  
  23. // block at this point for the future computation to complete
  24. Await.ready(firstOccurrence, Duration("1000 seconds"))
  25. }

Report this snippet  

You need to login to post a comment.