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


/ Published in: Scala
Save to your folder(s)

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


Copy this code and paste it in your HTML
  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


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.