9820638ab706ba0753da5ff1d574bc657da9b962
[controller.git] / opendaylight / md-sal / sal-akka-raft / src / main / java / org / opendaylight / controller / cluster / raft / FollowerLogInformationImpl.java
1 /*
2  * Copyright (c) 2014 Cisco 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
9 package org.opendaylight.controller.cluster.raft;
10
11 import com.google.common.base.Stopwatch;
12 import scala.concurrent.duration.FiniteDuration;
13
14 import java.util.concurrent.TimeUnit;
15 import java.util.concurrent.atomic.AtomicLong;
16
17 public class FollowerLogInformationImpl implements FollowerLogInformation {
18
19     private final String id;
20
21     private final AtomicLong nextIndex;
22
23     private final AtomicLong matchIndex;
24
25     private final Stopwatch stopwatch;
26
27     private final long followerTimeoutMillis;
28
29     public FollowerLogInformationImpl(String id, long nextIndex,
30         long matchIndex, FiniteDuration followerTimeoutDuration) {
31         this.id = id;
32         this.nextIndex = new AtomicLong(nextIndex);
33         this.matchIndex = new AtomicLong(matchIndex);
34         this.stopwatch = new Stopwatch();
35         this.followerTimeoutMillis = followerTimeoutDuration.toMillis();
36     }
37
38     public long incrNextIndex(){
39         return nextIndex.incrementAndGet();
40     }
41
42     @Override
43     public long decrNextIndex() {
44         return nextIndex.decrementAndGet();
45     }
46
47     @Override
48     public void setNextIndex(long nextIndex) {
49         this.nextIndex.set(nextIndex);
50     }
51
52     public long incrMatchIndex(){
53         return matchIndex.incrementAndGet();
54     }
55
56     @Override
57     public void setMatchIndex(long matchIndex) {
58         this.matchIndex.set(matchIndex);
59     }
60
61     public String getId() {
62         return id;
63     }
64
65     public AtomicLong getNextIndex() {
66         return nextIndex;
67     }
68
69     public AtomicLong getMatchIndex() {
70         return matchIndex;
71     }
72
73     @Override
74     public boolean isFollowerActive() {
75         long elapsed = stopwatch.elapsed(TimeUnit.MILLISECONDS);
76         return (stopwatch.isRunning()) && (elapsed <= followerTimeoutMillis);
77     }
78
79     @Override
80     public void markFollowerActive() {
81         if (stopwatch.isRunning()) {
82             stopwatch.reset();
83         }
84         stopwatch.start();
85     }
86
87     @Override
88     public void markFollowerInActive() {
89         if (stopwatch.isRunning()) {
90             stopwatch.stop();
91         }
92     }
93 }