Akka serialization module has been documented extensively under the :ref:`serialization-scala` section. In this section we will point out the different APIs that are available in Akka for Java based serialization of ActorRefs. The Scala APIs of ActorSerialization has implicit Format objects that set up the type class based serialization. In the Java API, the Format objects need to be specified explicitly.
The following JUnit snippet first creates an actor using the default constructor. The actor is, as we saw above a stateless one. Then it is serialized and de-serialized to get back the original actor. Being stateless, the de-serialized version behaves in the same way on a message as the original actor.
..code-block:: java
@Test public void mustBeAbleToSerializeAfterCreateActorRefFromClass() {
Let's now have a look at how to serialize an actor that carries a state with it. Here the expectation is that the serialization of the actor will also persist the state information. And after de-serialization we will get back the state with which it was serialized.
Step 1: Define the Actor
Here we consider an actor defined in Scala. We will however serialize using the Java APIs.
..code-block:: scala
class MyUntypedActor extends UntypedActor {
var count = 0
def onReceive(message: Any): Unit = message match {
case m: String if m == "hello" =>
count = count + 1
getContext.replyUnsafe("world " + count)
case m: String =>
count = count + 1
getContext.replyUnsafe("hello " + m + " " + count)
case _ =>
throw new Exception("invalid message type")
}
}
Note the actor has a state in the form of an Integer. And every message that the actor receives, it replies with an addition to the integer member.
Step 2: Define the instance of the typeclass
..code-block:: java
class MyUntypedActorFormat implements Format<MyUntypedActor> {
@Override
public MyUntypedActor fromBinary(byte[] bytes, MyUntypedActor act) {
ProtobufProtocol.Counter p =
(ProtobufProtocol.Counter) new SerializerFactory().getProtobuf().fromBinary(bytes, ProtobufProtocol.Counter.class);