Fix followerDistributedDataStore tear down
[controller.git] / opendaylight / md-sal / sal-akka-raft / src / main / java / org / opendaylight / controller / cluster / raft / TimedRunnable.java
1 /*
2  * Copyright (c) 2015 Brocade Communications Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.controller.cluster.raft;
9
10 import static java.util.Objects.requireNonNull;
11
12 import akka.actor.Cancellable;
13 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
14 import scala.concurrent.duration.FiniteDuration;
15
16 /**
17  * An abstract class that implements a Runnable operation with a timer such that if the run method isn't
18  * invoked within a timeout period, the operation is cancelled via {@link #doCancel}.
19  *
20  * <p>
21  * <b>Note:</b> this class is not thread safe and is intended for use only within the context of the same
22  * actor that's passed on construction. The run method must be called on this actor's thread dispatcher as it
23  * modifies internal state.
24  *
25  * @author Thomas Pantelis
26  */
27 abstract class TimedRunnable implements Runnable {
28     private final Cancellable cancelTimer;
29     private boolean canRun = true;
30
31     @SuppressFBWarnings(value = "MC_OVERRIDABLE_METHOD_CALL_IN_CONSTRUCTOR",
32         justification = "https://github.com/spotbugs/spotbugs/issues/1867")
33     TimedRunnable(final FiniteDuration timeout, final RaftActor actor) {
34         cancelTimer = requireNonNull(actor).getContext().system().scheduler()
35             .scheduleOnce(requireNonNull(timeout), actor.self(), (Runnable) this::cancel,
36                 actor.getContext().system().dispatcher(), actor.self());
37     }
38
39     @Override
40     public void run() {
41         if (canRun) {
42             canRun = false;
43             cancelTimer.cancel();
44             doRun();
45         }
46     }
47
48     private void cancel() {
49         canRun = false;
50         doCancel();
51     }
52
53     /**
54      * Overridden to perform the operation if not previously cancelled or run.
55      */
56     protected abstract void doRun();
57
58     /**
59      * Overridden to cancel the operation on time out.
60      */
61     protected abstract void doCancel();
62 }