What will be the parallel Java actor code for replacing standard synchronization with stream code

If I have this synchronized code that I want to replace with actors without synchronization, how?

public synchronized int incrementAndGet() {
  i = i + 1;
  return i;
}

and I have a bunch of users on a website where I need to return every increasing number ... how can I replace this code with a participant code that does not have synchronization, so it does not block the synchronization code. which, I think, will be able to run it on multicores, etc. (Isn't that the goal of the participants?).

+5
source share
3 answers

Simple acting packaging iin an internal state:

case object Inc

class IncrementingActor extends Actor {
    var i = 0

    protected def receive = {
        case Inc =>
            i += 1
            sender ! i
    }
}

And blocking use (you need to get it somehow incrementAndGet):

import akka.pattern.ask

def incrementAndGet() = 
  Await.result((incrementingActor ? Inc).mapTo[Int], 1 seconds)

: , . AtomicInteger?

+3

Concurrency - . , , concurrency .

JVM , , , .

, , , ask (?). tell (!), . , . , . , .

, - :

case object Inc
case class Count(i)

class IncrementingActor extends Actor {
   var i = 0
   protected def receive = {
     case Inc =>
        i += 1
        sender ! Count(i)
  }
}

class FooActor( counter: ActorRef ) extends Actor {
  protected def receive = {
    case DoSomething() => {
      // Perform some work
      counter ! Inc
    }
    case Count(i) => {
      // Do something with the counter result   
    }
  }
}
+3

( incrementAndGet()) , . . , AtomicInteger .

0

All Articles