Using future callback inside akka actor

前端 未结 4 1613
我在风中等你
我在风中等你 2021-02-13 12:24

I\'ve found in Akka docs:

When using future callbacks, such as onComplete, onSuccess, and onFailure, inside actors you need to carefully avoid closing ove

4条回答
  •  暖寄归人
    2021-02-13 12:47

    It means this:

    class NotThreadSafeActor extends Actor {
    
      import context.dispatcher
    
      var counter = 0
    
      def receive = {
        case any =>
          counter = counter + 1
          Future {
            // do something else on a future
            Thread.sleep(2000)
          }.onComplete {
            _ => counter = counter + 1
          }
      }
    }
    

    In this example, both the actor's receive method, and the Future's onComplete change the mutable variable counter. In this toy example its easier to see, but the Future call might be nested methods that equally capture a mutable variable.

    The issue is that the onComplete call might execute on a different thread to the actor itself, so its perfectly possible to have one thread executing receive and another executing onComplete thus giving you a race condition. Which negates the point of an actor in the first place.

提交回复
热议问题