0

I have a procedure that continuously updates a value. I want to be able to periodically query the operation for the current value. In my particular example, every update can be considered an improvement and the procedure will eventually converge on a final, best answer, but I want/need access to the intermediate results. The speed with which the loop executes and the time it takes to converge matters.

As an example, consider this loop:

var current = 0
while(current < 100){
  current = current + 1
}

I want to be able to get value of current on any loop iteration.

A solution with an Actor would be:

class UpdatingActor extends Actor{
  var current : Int = 0
  def receive = {
    case Update => {
      current = current + 1
      if (current < 100) self ! Update
    }
    case Query => sender ! current
  }
}

You could get rid of the var using become or FSM, but this example is more clear IMO.

Alternatively, one actor could run the operation and send updated results on every loop iteration to another actor, whose sole responsibility is updating the value and responding to queries about it. I don't know much about "agents" in Akka, but this seems like a potential use case for one.

What are better/alternative ways of doing this using Scala? I don't need to use actors; that was just one solution that came to mind.

1

2 Answers 2

1

Your actor-based solution is ok.

Sending the intermediate result after each change to a "result provider" actor would be a good idea as well if the calculation blocks the actor for a long time and you want to make sure that you can always get the intermediate result. Another alternative would be to make the actual calculator actor a child of the actor that collects the best result. That way the thing acts as a single actor from the outside, and you have the actor that has state (the current best result) separated from the actor that does the computation, which might fail.

An agent would be a solution somewhat between the very low level @volatile/AtomicInteger approach and an Actor. An agent is something that can only be modified by running a transform on it (and there is a queue for transforms), but which has a current state that can always be accessed. It is not location transparent though. so stay with the actor approach if you need that.

Here is how you would solve this with an agent. You have one thread which does a long-running calculation (simulated by Thread.sleep) and another thread that just prints out the best current result in regular intervals (also simulated by Thread.sleep).

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._
import scala.concurrent._
import akka.agent.Agent

object Main extends App {
  val agent = Agent(0)

  def computation() : Unit = {
    for(i<-0 until 100) {
      agent.send { current => 
        Thread.sleep(1000) // to simulate a long-running computation
        current + 1
      }
    }
  }

  def watch() : Unit = {
    while(true) {
      println("Current value is " + agent.get)
      Thread.sleep(1000)
    }
  }

  global.execute(new Runnable {
    def run() = computation
  })
  watch()
}

But all in all I think an actor-based solution would be superior. For example you could do the calculation on a different machine than the result tracking.

0

The scope of the question is a little wide, but I'll try :)

First, your example is perfectly fine, I don't see the point of getting rid of the var. This is what actors are for: protect mutable state.

Second, based on what you describe you don't need an actor at all.

class UpdatingActor {
  private var current = 0
  def startCrazyJob() {
    while(current < 100){
      current = current + 1
    }
  }

  def soWhatsGoingOn: Int = current 
}

You just need one thread to call startCrazyJob and a second one that will periodically call soWhatsGoingOn.

IMHO, the actor approach is better, but it's up to you to decide if it's worth importing the akka library just for this use case.

2
  • If you want to be sure that the outside world really sees current, you would either have to mark it as @volatile or use an AtomicInteger for it. The bad thing is that it will usually work without any of this because there will be some synchronization going on in other part of the program at the same time. But the java memory model does not guarantee it, and in fact if you run only startCrazyJob() and then poll soWhatsGoingOn from another thread you might see it stuck at 0. That is why actors are so great. If you use them correctly you don't have to understand the java memory model. Nov 7, 2013 at 15:35
  • Totally agree. I was just trying to keep the code very simple, I wanted to put an AtomicInteger but decided that it was not essential to understand the proposal :)
    – vptheron
    Nov 7, 2013 at 16:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.