Fix checkstyle reported by odlparent-3.0.0
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / datastore / jmx / mbeans / shard / OnDemandShardStateCache.java
1 /*
2  * Copyright (c) 2017 Inocybe Technologies 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.datastore.jmx.mbeans.shard;
9
10 import akka.actor.ActorRef;
11 import akka.pattern.Patterns;
12 import akka.util.Timeout;
13 import com.google.common.base.Preconditions;
14 import com.google.common.base.Stopwatch;
15 import com.google.common.cache.Cache;
16 import com.google.common.cache.CacheBuilder;
17 import java.util.concurrent.TimeUnit;
18 import org.opendaylight.controller.cluster.datastore.messages.OnDemandShardState;
19 import org.opendaylight.controller.cluster.raft.client.messages.GetOnDemandRaftState;
20 import scala.concurrent.Await;
21
22 /**
23  * Maintains a short-lived shared cache of OnDemandShardState.
24  *
25  * @author Thomas Pantelis
26  */
27 class OnDemandShardStateCache {
28     private static final Cache<String, OnDemandShardState> ONDEMAND_SHARD_STATE_CACHE =
29             CacheBuilder.newBuilder().expireAfterWrite(2, TimeUnit.SECONDS).build();
30
31     private final ActorRef shardActor;
32     private final String shardName;
33     private volatile String stateRetrievalTime;
34
35     OnDemandShardStateCache(final String shardName, final ActorRef shardActor) {
36         this.shardName = Preconditions.checkNotNull(shardName);
37         this.shardActor = shardActor;
38     }
39
40     OnDemandShardState get() throws Exception {
41         if (shardActor == null) {
42             return OnDemandShardState.newBuilder().build();
43         }
44
45         return ONDEMAND_SHARD_STATE_CACHE.get(shardName, this::retrieveState);
46     }
47
48     String getStatRetrievaelTime() {
49         return stateRetrievalTime;
50     }
51
52     private OnDemandShardState retrieveState() throws Exception {
53         stateRetrievalTime = null;
54         Timeout timeout = new Timeout(10, TimeUnit.SECONDS);
55         Stopwatch timer = Stopwatch.createStarted();
56
57         OnDemandShardState state = (OnDemandShardState) Await.result(Patterns.ask(shardActor,
58                 GetOnDemandRaftState.INSTANCE, timeout), timeout.duration());
59
60         stateRetrievalTime = timer.stop().toString();
61         return state;
62     }
63 }