user1768906
user1768906

Reputation:

Akka actors concurrency issue

Suppose I have three Actors communicate with each other: ActorControl, ActorA, ActorB.

ActorA and ActorB communicate with ActorControl. The messages they receive are mostly different but they also have one same message X. When they get X they both need to perform function Y.

To avoid duplicate code I took out the function Y to package object called common.

In this case it could happen that both ActorA and ActorB calling common.Y at the exact same time.

My question is whether this way I sabotaging the actors concurrency?

Upvotes: 2

Views: 355

Answers (1)

paradigmatic
paradigmatic

Reputation: 40461

You can share code across actors, but you cannot share data. If your functions are pure (stateless and without side effects), then there are no problems at all.

Here are some examples:

object Helper {

  // Safe
  def incrementPure( total: Int, i: Int ) = total + i

  //Unsafe
  private var total = 0
  def incrementStateful( i: Int ) = { total += i; total }

  //Unsafe
  def incrementSideEffect( i: Int ) = {
    val total = readCurrentTotal()
    val total2 = total + i
    saveCurrentTotal( total2 )
    total2
  }

}

In the last two functions, you should provide some sort of synchronization. However, this can potentially affect performances, if you rely on parallelism.

Upvotes: 4

Related Questions