filter-valve: use lambdas
[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 akka.actor.Cancellable;
11 import com.google.common.base.Preconditions;
12 import scala.concurrent.duration.FiniteDuration;
13
14 /**
15  * An abstract class that implements a Runnable operation with a timer such that if the run method isn't
16  * invoked within a timeout period, the operation is cancelled via {@link #doCancel}.
17  *
18  * <p>
19  * <b>Note:</b> this class is not thread safe and is intended for use only within the context of the same
20  * actor that's passed on construction. The run method must be called on this actor's thread dispatcher as it
21  * modifies internal state.
22  *
23  * @author Thomas Pantelis
24  */
25 abstract class TimedRunnable implements Runnable {
26     private final Cancellable cancelTimer;
27     private boolean canRun = true;
28
29     TimedRunnable(FiniteDuration timeout, RaftActor actor) {
30         Preconditions.checkNotNull(timeout);
31         Preconditions.checkNotNull(actor);
32         cancelTimer = actor.getContext().system().scheduler().scheduleOnce(timeout, actor.self(),
33                 (Runnable) () -> cancel(), actor.getContext().system().dispatcher(), actor.self());
34     }
35
36     @Override
37     public void run() {
38         if (canRun) {
39             canRun = false;
40             cancelTimer.cancel();
41             doRun();
42         }
43     }
44
45     private void cancel() {
46         canRun = false;
47         doCancel();
48     }
49
50     /**
51      * Overridden to perform the operation if not previously cancelled or run.
52      */
53     protected abstract void doRun();
54
55     /**
56      * Overridden to cancel the operation on time out.
57      */
58     protected abstract void doCancel();
59 }