pekko/akka-docs/java/code/akka/docs/transactor/FriendlyCounter.java

40 lines
1 KiB
Java
Raw Normal View History

/**
* Copyright (C) 2009-2011 Typesafe Inc. <http://www.typesafe.com>
*/
2010-11-12 16:09:31 +13:00
package akka.docs.transactor;
2010-11-12 16:09:31 +13:00
//#class
import akka.actor.*;
import akka.transactor.*;
2010-11-12 16:09:31 +13:00
import java.util.Set;
import scala.concurrent.stm.*;
2010-11-12 16:09:31 +13:00
public class FriendlyCounter extends UntypedTransactor {
Ref<Integer> count = Stm.ref(0);
2010-11-12 16:09:31 +13:00
@Override public Set<SendTo> coordinate(Object message) {
if (message instanceof Increment) {
Increment increment = (Increment) message;
if (increment.hasFriend())
return include(increment.getFriend(), new Increment());
}
return nobody();
}
public void atomically(InTxn txn, Object message) {
2010-11-12 16:09:31 +13:00
if (message instanceof Increment) {
Integer newValue = count.get(txn) + 1;
count.set(newValue, txn);
2010-11-12 16:09:31 +13:00
}
}
@Override public boolean normally(Object message) {
if ("GetCount".equals(message)) {
getSender().tell(count.single().get());
2010-11-12 16:09:31 +13:00
return true;
} else return false;
}
}
//#class