Mercurial > repos > other > SevenLanguagesInSevenWeeks
diff 4-Scala/sizer/src/main/scala/example/sizer.scala @ 70:4198fa4e0df4
Add Scala code and notes
author | IBBoard <dev@ibboard.co.uk> |
---|---|
date | Sat, 14 Oct 2017 13:39:41 +0100 |
parents | |
children |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/4-Scala/sizer/src/main/scala/example/sizer.scala Sat Oct 14 13:39:41 2017 +0100 @@ -0,0 +1,64 @@ +package example + +import scala.io._ +import akka.actor.{Actor,ActorSystem,Props} + +object PageLoader { + def getPageSize(url : String) : Int = { + try { + return Source.fromURL(url).mkString.length + } catch { + case e:Exception => + return -1 + } + } +} + +class ConcurrentActor extends Actor { + def receive = { + case (url, size) => println("Size for " + url + ": " + size) + } +} + +object Main { + val urls = List( + "https://www.amazon.com/", + "https://twitter.com/", + "https://www.google.co.uk/", + "https://www.bbc.co.uk/news/" + ) + + val system = ActorSystem("MySystem") + val actor = system.actorOf(Props[ConcurrentActor], name="concurrent-actor") + + def timeMethod(method: () => Unit) = { + val start = System.nanoTime + method() + val end = System.nanoTime + println("+++ Method took " + (end - start) / 1000000000.0 + " seconds.") + } + + def getPageSizeSequentially() = { + for (url <- urls) { + println("Size for " + url +": " + PageLoader.getPageSize(url)) + } + } + + def getPageSizeConcurrently() = { + for (url <- urls) { + // Send a message to the actor (which won't arrive until the PageLoader call completes) + println(s"Sending message for $url") + actor ! (url, PageLoader.getPageSize(url)) + } + } + + def main(args: Array[String]) { + println("Sequential:") + timeMethod { getPageSizeSequentially } + + println("Concurrent:") + timeMethod { getPageSizeConcurrently } + system.stop(actor) + system.terminate() + } +} \ No newline at end of file