Return to Snippet

Revision: 65387
at November 26, 2013 07:49 by tedg


Updated Code
import scala.concurrent.{Future, future, Await}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration.Duration

/**
 * This program expects a text file containing the word "computation" 
 * in the directory C:\tmp. The file name is expected to be "myText.txt"
 */
object FutureTest extends App {
    val firstOccurrence: Future[Int] = future {
        val source = scala.io.Source.fromFile("C:\\tmp\\myText.txt")
        source.toSeq.indexOfSlice("computation")
    } 
    
    firstOccurrence.onSuccess {case n =>
        println(n); 
    }
    
    firstOccurrence.onFailure {case t =>
        println(t.getMessage())
    }
    
    // block at this point for the future computation to complete
    Await.ready(firstOccurrence, Duration("1000 seconds"))  
}

Revision: 65386
at November 26, 2013 03:43 by tedg


Initial Code
import scala.concurrent._
import scala.concurrent.ExecutionContext.Implicits.global

/**
 * This program expects a text file containing the word "computation" in the directory C:\tmp. The file name is expected to be "myText.txt"
 */
object FutureTest extends App {
    var done = false
    val firstOccurrence: Future[Int] = future {
        val source = scala.io.Source.fromFile("C:\\tmp\\myText.txt")
        source.toSeq.indexOfSlice("computation")
    } 
    
    firstOccurrence.onSuccess {case n =>
        println(n); 
        done = true
    }
    
    firstOccurrence.onFailure {case t =>
        println(t.getMessage())
        done = true
    }
    
    while (!done) {
        Thread.sleep(100)
    }
}

Initial URL

                                

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

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

Initial Tags

                                

Initial Language
Scala