Scala actors design patterns - part 4

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:

loop {
  reactWithin(0) // (1)
    case Cancel(id) => canecellations += id // (2)
    case TIMEOUT =>  // (3)
      react { 
        case Cancel(id) => () // oops, too late (4)
        case Task(id) =>  // (5)
          if (!cancellations(id)) { 
            // process task
          } else {
            cancellations -= id

(1) reactWithin(0) means that the queueu is searched right then and if no matching message is found, a TIMEOUT is fired. In our case, we only match Cancel messages, so they will be handled right away before any Task

(2) Since Cancel is processed before Task, we need to remember that we're about to process a Task with the same ID.

(3) A TIMEOUT here means there are no Cancel messages in the queue. So we continue with regular processing using react

(4) A client may still send Cancel messages and we need to remove the from the queu

(5) Process the Task message if no cancellation was found.

Thank you for your interest!

We will contact you as soon as possible.

Send us a message

Oops, something went wrong
Please try again or contact us by email at