Over a million developers have joined DZone.

Use Scala’s DynamicVariable to Avoid Closing Over a Value in Akka

DZone's Guide to

Use Scala’s DynamicVariable to Avoid Closing Over a Value in Akka

· Java Zone
Free Resource

Learn how our document data model can map directly to how you program your app, and native database features like secondary indexes, geospatial and text search give you full access to your data. Brought to you in partnership with MongoDB.

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?


    class Caplin extends Actor {
      def recieve = {
        case _ => Future { sender ! "カピバラ" } // OUCH!

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

    class Caplin extends Actor {
      def recieve = {
        case _ =>
          val mySender = sender
          Future { mySender ! "カピバラ" }

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

    class Caplin extends Actor {
      val Sender = new DynamicVariable[ActorRef](self)
      def recieve = {
        case "カピバラ" => "Why am I talking with myself?"
        case _         =>
          Sender.withValue(sender) {
            Future { Sender.value ! "カピバラ" }

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.

Discover when your data grows or your application performance demands increase, MongoDB Atlas allows you to scale out your deployment with an automated sharding process that ensures zero application downtime. Brought to you in partnership with MongoDB.


Published at DZone with permission of Konrad Malawski, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}