2 * Copyright (c) 2015 Brocade Communications Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.controller.cluster.raft;
10 import static java.util.Objects.requireNonNull;
12 import akka.actor.Cancellable;
13 import scala.concurrent.duration.FiniteDuration;
16 * An abstract class that implements a Runnable operation with a timer such that if the run method isn't
17 * invoked within a timeout period, the operation is cancelled via {@link #doCancel}.
20 * <b>Note:</b> this class is not thread safe and is intended for use only within the context of the same
21 * actor that's passed on construction. The run method must be called on this actor's thread dispatcher as it
22 * modifies internal state.
24 * @author Thomas Pantelis
26 abstract class TimedRunnable implements Runnable {
27 private final Cancellable cancelTimer;
28 private boolean canRun = true;
30 TimedRunnable(final FiniteDuration timeout, final RaftActor actor) {
31 cancelTimer = requireNonNull(actor).getContext().system().scheduler()
32 .scheduleOnce(requireNonNull(timeout), actor.self(), (Runnable) this::cancel,
33 actor.getContext().system().dispatcher(), actor.self());
45 private void cancel() {
51 * Overridden to perform the operation if not previously cancelled or run.
53 protected abstract void doRun();
56 * Overridden to cancel the operation on time out.
58 protected abstract void doCancel();