Quantcast
Channel: Akka Libraries - Discussion Forum for Akka technologies
Viewing all articles
Browse latest Browse all 1367

Mutable State in conflateWithSeed functions

$
0
0

@gabor-aranyossy wrote:

I understand that conflateWithSeed was meant to be used with a fold-style pure function application, but I was wondering whether it is safe to use a mutable data structure to accumulate state like in this example below.

The function aggregate is being called by different threads, but I assume memory barriers are applied by Akka when different threads execute the Actor logic.


  implicit val sys = ActorSystem()
  implicit val mat = ActorMaterializer()

  def seed(i: Int): mutable.LinkedHashMap[Int, Int] = mutable.LinkedHashMap[Int, Int](i -> 1)

  def aggregate(state: mutable.LinkedHashMap[Int, Int], i: Int): mutable.LinkedHashMap[Int, Int] = {
    state.put(i, state.getOrElseUpdate(i, 0) + 1)
    state
  }

  Source(1 to 10000)
    .map(_ => Random.nextInt(100))
    .conflateWithSeed(seed)(aggregate)
    .throttle(1, 1.second)
    .runForeach(println)
}

Posts: 8

Participants: 3

Read full topic


Viewing all articles
Browse latest Browse all 1367

Trending Articles