All Downloads are FREE. Search and download functionalities are using the official Maven repository.

eu.lucaventuri.fibry.CustomActor Maven / Gradle / Ivy

There is a newer version: 3.0.1
Show newest version
package eu.lucaventuri.fibry;

import eu.lucaventuri.functional.Either3;

import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Function;

public abstract class CustomActor extends BaseActor {
    protected final Consumer> actorLogicReturn;

    protected CustomActor(MiniQueue>, T, MessageWithAnswer>> queue, Consumer finalizer, CloseStrategy closeStrategy, int pollTimeoutMs) {
        super(queue, finalizer, closeStrategy, pollTimeoutMs, null, null);

        Function tmpLogicReturn = ActorUtils.discardingToReturning(this::onMessage);

        this.actorLogicReturn = mwr -> mwr.answer.complete(tmpLogicReturn.apply(mwr.message));
    }

    protected CustomActor(MiniQueue>, T, MessageWithAnswer>> queue, Consumer finalizer, int pollTimeoutMs) {
        this(queue, finalizer, null, pollTimeoutMs);
    }

    protected abstract void onMessage(T message);
    protected void onNoMessages() { }

    protected void takeAndProcessSingleMessage() throws InterruptedException {
        Either3>, T, MessageWithAnswer> message = queue.take();

        message.ifEither(cns -> cns.accept(this), this::onMessage, actorLogicReturn::accept);
    }

    @Override
    protected void takeAndProcessSingleMessageTimeout() throws InterruptedException {
        Either3>, T, MessageWithAnswer> message = queue.poll(pollTimeoutMs, TimeUnit.MILLISECONDS);

        if (message != null)
            message.ifEither(cns -> cns.accept(this), this::onMessage, actorLogicReturn::accept);
        else
            onNoMessages();
    }

    @Override
    protected BaseActor recreate() {
        throw new UnsupportedOperationException("Receiving actors do not support auto healing");
    }
}