Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When are threads created for Scala actor's reacts?

Tags:

scala

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 pending. It doesn't seem to be the case.

import scala.actors.Actor
import scala.actors.Actor._

class SleepyReactor extends Actor {
    def act() {
        loop {
            react {
                case x => {
                    println("reacting to %s on thread %s".format(x, Thread.currentThread.getName))
                    Thread.sleep(1000)
                    println("done with " + x)
                }
            }
        }
    }
}
val sleepyOne = new SleepyReactor
sleepyOne.start
sleepyOne ! "first" // runs on thread-5

// wait until completion

sleepyOne ! "second" // runs on thread-3

Can someone explain why these react's are running on different threads and when a new thread is created for an actor with react?

I read somewhere react is event based, and I took that to mean that "react actors" shared a thread and if one was "reacting" the other "react actors" would be queued until the first was done. I now think I am wrong. How does this work, and how is it different than receive?

like image 499
agilefall Avatar asked Oct 06 '09 17:10

agilefall


2 Answers

It is true that for a pure event-based actor, its reacting code runs on the same thread as message sending code.

But in Scala, since it's not desirable to block a thread when an actor calls a blocking operation inside its react code and to unify event-based and thread-based actors(being able to compose them), both type of actors uses the same thread pool but the thread-based actors get their own threads whereas event-based actors shares threads based on a task queue. For details, please see Actors that Unify Threads and Events by Philipp Haller and Martin Odersky

like image 192
Walter Chang Avatar answered Sep 21 '22 08:09

Walter Chang


Don't assume a separate thread per Actor. The Scala machinery creates a pool of worker threads and only grows that pool if the size of 'blocked' Actors is greater than the pool size. When your actor calls receive, it's in a blocked state until it receives its message.

like image 33
andyczerwonka Avatar answered Sep 17 '22 08:09

andyczerwonka