User Guide Actors

User Guide Actors

Get Starting

A finite state machine actor class is provided to easily create an active class whose behavior is defined through a finite state machine

class FsmActor<O extends FsmActor<O, S, E>, S extends Enum<S>, E extends Enum<E>> extends Actor<Event<?>, Void> {
    private static final Logger logger = LoggerFactory.getLogger();
    private final StateMachine<O, S, E> fsm;

    public FsmActor(@Nonnull FsmBuilder<O, S, E> builder, String name) throws SuspendExecution {
         super(name, new MailboxConfig());
         fsm = builder.machine(name, (O) this);
         spawn();
         try {
             register(name);
         } catch (SuspendExecution e) {
             logger.error("Could not register actor {} in name registry due {}", name, e);
         }
   }

    public void process(@Nonnull Event<E> event) throws SuspendExecution {
        self().send(event);
    }

    protected Void doRun() throws InterruptedException, SuspendExecution {
        for (; ; ) {
            Event<?> event = receive();
            fsm.fire((Event<E>) event);
            if (fsm.isFinal()) {
                return null;
            }
        }
    }
}

You can find an example of how to create FSM actor derived classes in the tests in package net.tangly.fsm.actors.

Actors and Finite State Machine

actors-and-fsm

Messages

The message sent to a finite state machine instance is a regular event instance with a generic parameter being the enumeration of all event kinds the machine should process.

You send a message to a quasar actor with the following snippet such as. The run method of the FSM actor will retrieve the event from the message queue of the quasar actor instance and dispatch it to the finite state machine instance

ActorRef<Object> clientRef = ActorRegistry.getActor(clientName);
clientRef.send(new Event<Events>(Events.Response, List.of(clientName, self())));

If you have reference to the FSM actor instance use the convenience method process such as

client.process(new Event<>(Events.Inquiry));

Actors Communication

actors-communication