by ittayd
border:

The thread pool used by the Scala actors may not work liike you think it should, causing actors to starve.

 

To see why, lets first define a utility method to measure how long an actor takes to act. We take a timestamp, then create an actor that just prints to the console how many milliseconds passed since the timestamp

 

 

import scala.actors.Actor._

def timeActor = {
    val start = System.currentTimeMillis
    actor {println("Took: " + (System.currentTimeMillis - start))}
}

 

Testing it:

by ittayd
border:

This time, a short explanation on how to prioritize messages.

 

In this example, the actor has two messages: Task(id) and Cancel(id). What happens if we send (several) Task messages and then want to cancel one of them? The following doesn't work:

loop {
  react {
    case Task(id) => ...
    case Cancel(id) => ....
  }
}

 

The reason is that the Task messages are before the Cancel message and so will be processed before processing it.

 

The right way is the following:

by ittayd
border:

 Actors process messages one at a time. But what if processing a message is a read-only process? Why not be able to process them simultaneously?

 

I’ll first show a direct implementation of the pattern and then a trait that can be reused.

 

First, assume we have 2 messages  for that stand for a read operation and for a write operation (the parameter i is used for print-debug to keep track of what message is processed):

 

by ittayd
border:

 In the previous post, I discussed how to handle sending data from an actor in response to a message (request) from another. This time I want to discuss how to handle that response.

 

In the simple case, an actor sends a request, and awaits a response:

 

by ittayd
border:

 One of my pain points with the actors library is how to handle replies to a message. The library provides the methods ‘!?’ and ‘!!’, but without type safety. Client code needs to cast the reply to the expected type:

 

by ittayd
border:

 This post is one of (hopefully) a series of design patterns for actor based programming. If you don’t know what an actor based programming is, see http://en.wikipedia.org/wiki/Actor_model. This post and the next will be focused on developing in Scala, using its standard actors library.