70
|
1 package example
|
|
2
|
|
3 import scala.io._
|
|
4 import akka.actor.{Actor,ActorSystem,Props}
|
|
5
|
|
6 object PageLoader {
|
|
7 def getPageSize(url : String) : Int = {
|
|
8 try {
|
|
9 return Source.fromURL(url).mkString.length
|
|
10 } catch {
|
|
11 case e:Exception =>
|
|
12 return -1
|
|
13 }
|
|
14 }
|
|
15 }
|
|
16
|
|
17 class ConcurrentActor extends Actor {
|
|
18 def receive = {
|
|
19 case (url, size) => println("Size for " + url + ": " + size)
|
|
20 }
|
|
21 }
|
|
22
|
|
23 object Main {
|
|
24 val urls = List(
|
|
25 "https://www.amazon.com/",
|
|
26 "https://twitter.com/",
|
|
27 "https://www.google.co.uk/",
|
|
28 "https://www.bbc.co.uk/news/"
|
|
29 )
|
|
30
|
|
31 val system = ActorSystem("MySystem")
|
|
32 val actor = system.actorOf(Props[ConcurrentActor], name="concurrent-actor")
|
|
33
|
|
34 def timeMethod(method: () => Unit) = {
|
|
35 val start = System.nanoTime
|
|
36 method()
|
|
37 val end = System.nanoTime
|
|
38 println("+++ Method took " + (end - start) / 1000000000.0 + " seconds.")
|
|
39 }
|
|
40
|
|
41 def getPageSizeSequentially() = {
|
|
42 for (url <- urls) {
|
|
43 println("Size for " + url +": " + PageLoader.getPageSize(url))
|
|
44 }
|
|
45 }
|
|
46
|
|
47 def getPageSizeConcurrently() = {
|
|
48 for (url <- urls) {
|
|
49 // Send a message to the actor (which won't arrive until the PageLoader call completes)
|
|
50 println(s"Sending message for $url")
|
|
51 actor ! (url, PageLoader.getPageSize(url))
|
|
52 }
|
|
53 }
|
|
54
|
|
55 def main(args: Array[String]) {
|
|
56 println("Sequential:")
|
|
57 timeMethod { getPageSizeSequentially }
|
|
58
|
|
59 println("Concurrent:")
|
|
60 timeMethod { getPageSizeConcurrently }
|
|
61 system.stop(actor)
|
|
62 system.terminate()
|
|
63 }
|
|
64 } |