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

eu.lucaventuri.fibry.CustomActorWithResult 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;

public abstract class CustomActorWithResult extends BaseActor {
    protected final Consumer actorLogic;

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

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

        this.actorLogic = ActorUtils.returningToDiscarding(this::onMessage);
    }

    protected abstract R onMessage(T message);

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

        message.ifEither(cns -> cns.accept(this), actorLogic::accept, mwr -> mwr.answer.complete(onMessage(mwr.message)));
    }

    @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, mwr -> mwr.answer.complete(onMessage(mwr.message)));
    }

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