Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what would be the parallel java "actor" code to replace standard synchronization with threads code

If i have this synchronized code which i want to replace with actors with no synchronization, how?

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

and i have a bunch of users in web site where i need to return each an incrementing number... how can i replace that code with actors code which have no synchronizations thus have no blocking synchronizing code. which i guess would thenn be able to run it on multicores etc (isn't that the purpose of actors?).

like image 316
Jas Avatar asked Apr 13 '12 18:04

Jas


1 Answers

A simple actor wrapping i in its internal state:

case object Inc

class IncrementingActor extends Actor {
    var i = 0

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

And blocking usage (you need to obtain incrementAndGet somehow):

import akka.pattern.ask

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

This code is: slow, complicated and non-idiomatic. What about AtomicInteger?

like image 117
Tomasz Nurkiewicz Avatar answered Nov 15 '22 04:11

Tomasz Nurkiewicz