2011-12-21 21:32:20 +13:00
|
|
|
/**
|
2012-01-19 18:21:06 +01:00
|
|
|
* Copyright (C) 2009-2012 Typesafe Inc. <http://www.typesafe.com>
|
2011-12-21 21:32:20 +13:00
|
|
|
*/
|
|
|
|
|
|
2012-05-22 11:37:09 +02:00
|
|
|
package docs.transactor;
|
2011-12-21 21:32:20 +13:00
|
|
|
|
|
|
|
|
//#class
|
|
|
|
|
import akka.actor.*;
|
|
|
|
|
import akka.transactor.*;
|
2012-01-18 15:59:59 +13:00
|
|
|
import scala.concurrent.stm.Ref;
|
2012-02-06 11:34:47 +13:00
|
|
|
import scala.concurrent.stm.japi.STM;
|
2011-12-21 21:32:20 +13:00
|
|
|
|
|
|
|
|
public class CoordinatedCounter extends UntypedActor {
|
2012-02-06 11:34:47 +13:00
|
|
|
private Ref.View<Integer> count = STM.newRef(0);
|
2011-12-21 21:32:20 +13:00
|
|
|
|
|
|
|
|
public void onReceive(Object incoming) throws Exception {
|
|
|
|
|
if (incoming instanceof Coordinated) {
|
|
|
|
|
Coordinated coordinated = (Coordinated) incoming;
|
|
|
|
|
Object message = coordinated.getMessage();
|
|
|
|
|
if (message instanceof Increment) {
|
|
|
|
|
Increment increment = (Increment) message;
|
|
|
|
|
if (increment.hasFriend()) {
|
2012-09-26 10:56:25 +02:00
|
|
|
increment.getFriend().tell(
|
|
|
|
|
coordinated.coordinate(new Increment()), getSelf());
|
2011-12-21 21:32:20 +13:00
|
|
|
}
|
2012-01-18 15:59:59 +13:00
|
|
|
coordinated.atomic(new Runnable() {
|
|
|
|
|
public void run() {
|
2012-02-06 11:34:47 +13:00
|
|
|
STM.increment(count, 1);
|
2011-12-21 21:32:20 +13:00
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
} else if ("GetCount".equals(incoming)) {
|
2012-09-19 23:55:53 +02:00
|
|
|
getSender().tell(count.get(), getSelf());
|
2011-12-29 20:49:26 +01:00
|
|
|
} else {
|
|
|
|
|
unhandled(incoming);
|
2011-12-21 21:32:20 +13:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
//#class
|