io.vlingo.common.RepeatableCompletes Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of vlingo-common Show documentation
Show all versions of vlingo-common Show documentation
These are just a few common tools shared across various vlingo projects.
// Copyright © 2012-2020 VLINGO LABS. All rights reserved.
//
// This Source Code Form is subject to the terms of the
// Mozilla Public License, v. 2.0. If a copy of the MPL
// was not distributed with this file, You can obtain
// one at https://mozilla.org/MPL/2.0/.
package io.vlingo.common;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicBoolean;
public class RepeatableCompletes extends BasicCompletes {
public RepeatableCompletes(final Scheduler scheduler) {
super(new RepeatableActiveState(scheduler));
}
public RepeatableCompletes(final T outcome, final boolean succeeded) {
super(new RepeatableActiveState(), outcome, succeeded);
}
public RepeatableCompletes(final T outcome) {
super(new RepeatableActiveState(), outcome);
}
@Override
public Completes repeat() {
if (state.isOutcomeKnown()) {
state.repeat();
}
return this;
}
@Override
@SuppressWarnings("unchecked")
public Completes with(O outcome) {
super.with(outcome);
state.repeat();
return (Completes) this;
}
protected static class RepeatableActiveState extends BasicActiveState {
private final Queue> actionsBackup;
private final AtomicBoolean repeating;
protected RepeatableActiveState(final Scheduler scheduler) {
super(scheduler);
this.actionsBackup = new ConcurrentLinkedQueue<>();
this.repeating = new AtomicBoolean(false);
}
protected RepeatableActiveState() {
this(null);
}
@Override
public void backUp(final Action action) {
if (action != null) {
actionsBackup.add(action);
}
}
@Override
public void repeat() {
if (repeating.compareAndSet(false, true)) {
restore();
outcomeKnown(false);
repeating.set(false);
}
}
@Override
public void restore() {
while (actionsBackup.peek() != null) {
restore(actionsBackup.poll());
}
}
}
}