Akka for Java, how to use an actor with generics

Akka seems like a good concept for working with asynchronous threads in your application. I am currently studying Akka for one of my projects, and I was wondering how to properly design actors.

Imagine the following person:

public class SampleActor extends UntypedActor {
    private final LoggingAdapter log = 
            Logging.getLogger(getContext().system(), this);

    @Override
    public void onReceive(final Object message) throws Exception {
        if (message instanceof SomeType) {
            SomeType someType = ((SomeType) message);
            // Handle SomeType
        } else if (message instance SomeOtherType) {
            SomeOtherType someOtherType = ((SomeOtherType) message);
            // Handle SomeOtherType
        } else {
            unhandled(message);
        }
    }
}

The above code is a general scheme, which, for example, is described in the Akka documentation .

The sample above seems to me to be an old school with a bunch of checks instanceofand what the actor is processing Object. Is there any other preferred approach for this (for example, some kind of base class in which you specify the types that interest you) or similar.

, , , , , , :

public class SampleActor extends GenericActor<SomeType> {
    public void onReceive(final SomeType someType) throws Exception {
        // Do stuff
    }
}

, . UntypedActor - ?

+4
1

UntypedActor onReceive, Scala - .

Java, - . Visitor , .

AbstractActor PartialFunction<Object, BoxedUnit> receive(), .

public abstract class AbstractAggregateRegistryActor extends AbstractActor {

    @Override
    public PartialFunction<Object, BoxedUnit> receive() {
        return ReceiveBuilder.
                match(Protocol.AbstractComponentRegister.class, 
                                      this::handleRegistration).
                match(Protocol.AbstractComponentDeregister.class,
                                      this::handleDeregistration).
                match(Protocol.AbstractComponentRegistryRequest.class,
                                      this::handleRegistryRequest).
                matchAny(this::unhandled).build();
    }


    private void handleRegistration(Protocol.AbstractComponentRegister
                                    componentRegister) {
        .....
    }

    private void handleDeregistration(Protocol.AbstractComponentDeregister
                                      componentDeregister) {
        ...
    }

    protected abstract <T extends Protocol.AbstractComponentRegistryRequest> 
                         void handleRegistryRequest(T registryRequest);


    @Override
    public void unhandled(Object message) {
        log.warning("Unhandled message {} in registry.", message);
    }
}
+1

All Articles