Use Scala’s DynamicVariable to avoid closing over a value in Akka

Posted by Konrad 'ktoso' Malawski on 08/12/2012 – 00:57;

Note: As Steve points out in the comments this is actually NOT SAFE (the solution with DynamicVariable). (!)

If you’ve ever read Akka’s docs about Actors or saw this blogbost about how to avoid closing over the sender in Akka you already know why you shouldn’t close over the sender value when implementing actors with futures inside them. In this post we’ll discover a nice Scala utility class we can use to solve this problem.

But first… what is the problem?

// BROKEN! DON'T DO THIS AT HOME!
  1. class Caplin extends Actor {
  2.   def recieve = {
  3.     case _ => Future { sender ! "カピバラ" } // OUCH!
  4.   }
  5. }

The above code may fail, as the variable sender (it’s actually a method) is “shared mutable state”! Why? Well, there’s one instance of Caplin, yet the sender changes each time someone sends Caplin a message right? So while the future is executing, the value of sender may have changed (as another message just came in). The above code would then end up responding to the wrong sender.

Now with having the problem defined, let’s see how we can solve it. The obvious solution is to create a copy of the sender before we dispatch the Future, just like:

// this is OK
  1. class Caplin extends Actor {
  2.   def recieve = {
  3.     case _ =>
  4.       val mySender = sender
  5.       Future { mySender ! "カピバラ" }
  6.   }
  7. }

This works OK. But I promised to talk about scala.util.DynamicVariable in the blog post’s title, didn’t I? Let’s see how we could implement the same thing by using it then.

DynamicVariable is pretty much like Java’s ThreadLocal. It exposes a value, which may be set to different values per Thread – so that’s exactly what we need to safe-guard our code agains mixing up the sender values.

// dynamic variable version
  1. class Caplin extends Actor {
  2.   val Sender = new DynamicVariable[ActorRef](self)
  3.  
  4.   def recieve = {
  5.     case "カピバラ" => "Why am I talking with myself?"
  6.     case _         =>
  7.       Sender.withValue(sender) {
  8.         Future { Sender.value ! "カピバラ" }
  9.       }
  10.   } 
  11. }

As you can see, first we create the “thread-local” value Sender and before we dispatch the new Future we wrap the code with DynamicVariable::withValue which assures that within this block of code – the value of sender is guaranteed to be what we passed in there.

Where does the name DynamicVariable come from you might ask? It’s clearly not dynamic in the “Type” way – it’s strictly typed as you’d expect it to be. Well, turns out that what we see here is an implementation of Dynamic Scoping (read up about it on Wikipedia).

That’s it for now, check back later to see some more Scala in action, as I’m just in the middle of preparing my Scala + Android talk (version 2!). While this example maybe not the best case (it’s quite a bit of code compared to “just use a val”) on where to use DynamicVariable, I hope more of you are now aware of the close over sender issue, as well as this nice nifty class from Scala.

Tags: , , ,

This post is under “coding, english, scala” and has 2 respond so far.

2 Responds so far- Add one»

  1. 1. Steve Sowerby Said:

    But DynamicVariable uses a ThreadLocal (an InheritableThreadLocal in fact) which means this isn’t safe.
    If the future block is executed in a different thread to the actor’s receive (likely under load) you could end up with a null value.

  2. 2. Ktoso Said:

    Ouch – thanks for pointing this out! We don’t actually use it with actors, I was trying to come up with an use-case example to blog about DynamicVariable – seems I screwed up the example.

Post a reply