After reading about using react
in actors in Scala, I thought react
\'s would share the same thread given there weren\'t multiple react
\'s
To see the effect described in the previous answers, you need to generate more than two threads. This sample program generates 100 threads with receive and 100 threads with react.
When you run it, you can see that the receive actors each occupy a thread, and the react ones share a small number of threads. (It's easiest to see when you sort the output.)
import scala.actors._
import scala.actors.Actor._
class ReactActor extends Actor {
def act {
loop {
react {
case 'Hello => println("React: " + Thread.currentThread)
}
}
}
}
class ReceiveActor extends Actor {
def act {
while (true) {
receive {
case 'Hello => println("Receive: " + Thread.currentThread)
}
}
}
}
object Main {
def main(args: Array[String]) {
val count = 100
val as = new Array[Actor](2 * count)
for (i <- 0 until count) {
as(i) = new ReactActor
as(count + i) = new ReceiveActor
}
for (a <- as) a.start()
actor {
println(Thread.currentThread)
for (a <- as) a ! 'Hello
}
}
}
The sorted output in a typical program run:
Thread[Thread-102,5,main]
React: Thread[Thread-102,5,main]
React: Thread[Thread-102,5,main]
React: Thread[Thread-102,5,main]
...
React: Thread[Thread-102,5,main]
React: Thread[Thread-103,5,main]
React: Thread[Thread-103,5,main]
...
React: Thread[Thread-103,5,main]
React: Thread[Thread-104,5,main]
React: Thread[Thread-104,5,main]
React: Thread[Thread-104,5,main]
...
React: Thread[Thread-104,5,main]
React: Thread[Thread-105,5,main]
React: Thread[Thread-105,5,main]
React: Thread[Thread-105,5,main]
...
React: Thread[Thread-105,5,main]
Receive: Thread[Thread-1,5,main]
Receive: Thread[Thread-10,5,main]
Receive: Thread[Thread-100,5,main]
Receive: Thread[Thread-101,5,main]
Receive: Thread[Thread-11,5,main]
Receive: Thread[Thread-12,5,main]
Receive: Thread[Thread-13,5,main]
Receive: Thread[Thread-14,5,main]
Receive: Thread[Thread-15,5,main]
Receive: Thread[Thread-16,5,main]
Receive: Thread[Thread-17,5,main]
Receive: Thread[Thread-18,5,main]
Receive: Thread[Thread-19,5,main]
Receive: Thread[Thread-2,5,main]
Receive: Thread[Thread-20,5,main]
Receive: Thread[Thread-21,5,main]
...