Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
typing up the more real world actor example
- Loading branch information
Showing
1 changed file
with
44 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
import scala.io._ | ||
import scala.actors._ | ||
import Actor._ | ||
|
||
object PageLoader { | ||
def getPageSize(url : String) = Source.fromURL(url).mkString.length | ||
} | ||
|
||
val urls = List("http://twitter.com", | ||
"http://amazon.com", | ||
"http://themeforest.net") | ||
|
||
def timeMethod(method: () => Unit) = { | ||
val start = System.nanoTime | ||
method() | ||
val end = System.nanoTime | ||
println("Mthod took " + (end - start)/1000000000.0 + "seconds.") | ||
} | ||
|
||
def getPageSizeSequentially() = { | ||
for(url <- urls) { | ||
println("Size for " + url + ": " + PageLoader.getPageSize(url)) | ||
} | ||
} | ||
|
||
def getPageSizeConcurrently() = { | ||
val caller = self | ||
|
||
for(url <- urls) { | ||
actor { caller ! (url, PageLoader.getPageSize(url)) } | ||
} | ||
|
||
for(i <- 1 to urls.size) { | ||
receive { | ||
case (url, size) => println("Size for " + url + ": " + size) | ||
} | ||
} | ||
} | ||
|
||
println("Sequential") | ||
timeMethod { getPageSizeSequentially } | ||
println("Concurrent") | ||
timeMethod { getPageSizeConcurrently } | ||
|