Skip to content

Instantly share code, notes, and snippets.

@nt
Created June 6, 2012 16:47
Show Gist options
  • Save nt/2883202 to your computer and use it in GitHub Desktop.
Save nt/2883202 to your computer and use it in GitHub Desktop.
Concurrency in scala
import scala.actors.Actor._
import java.util.concurrent._
import scala.collection.mutable.ListBuffer
val terms = (1900 to 2012) map (i => "best party in "+i)
val pool = Executors.newFixedThreadPool(10)
var result = new ListBuffer[String]()
val sink = actor {
loop {
react {
case s:String => {
println("received "+s)
result += s
}
}
}
}
terms foreach (s => {
val r = new Runnable {
def run {
Thread.sleep(500)
sink ! s
}
}
pool.execute(r)
})
pool.shutdown()
while(result.length < terms.length) Thread.sleep(50)
println("finished")
println(result)
import scala.actors.Actor._
import java.util.concurrent._
import scala.collection.mutable.ListBuffer
import java.net.{URLConnection, URL}
import scala.io.Source
import scala.collection.mutable
val terms = (1950 to 2012) map (i => "best party in "+i)
val pool = Executors.newFixedThreadPool(10)
var result = mutable.Map.empty[String, String]
val sink = actor {
loop {
if(result.keys.size < terms.length) {
react {
case s:(String,String) => {
result += s
}
}
} else {
println("finished")
result foreach (p => {
println(p._1+": "+p._2.length)
})
pool.shutdown()
exit()
}
}
}
terms foreach (s => {
val r = new Runnable {
def run {
val u = "https://www.google.com/#q="+s
println("getting "+u)
val conn = new URL(u).openConnection()
conn.connect
val out = Source.fromInputStream(conn.getInputStream).mkString
sink ! s ->out
}
}
pool.execute(r)
})
import scala.actors.Actor._
import java.util.concurrent._
import scala.collection.mutable.ListBuffer
import java.net.{URLConnection, URL}
import scala.io.Source
import scala.collection.mutable
val terms = (1950 to 2012) map (i => "best party in "+i)
var result = mutable.Map.empty[String, String]
val sink = actor {
loop {
if(result.keys.size < terms.length) {
react {
case s:(String,String) => {
result += s
}
}
} else {
println(Thread.currentThread.getName+"\tfinished")
result foreach (p => {
println(Thread.currentThread.getName+"\t"+p._1+": "+p._2.length)
})
exit()
}
}
}
terms foreach (s => {
val a = actor {
val u = "https://www.google.com/#q="+s
println(Thread.currentThread.getName+"\tgetting "+u)
val conn = new URL(u).openConnection()
conn.connect
val out = Source.fromInputStream(conn.getInputStream).mkString
sink ! s ->out
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment