2 * Copyright (c) 2017 Inocybe Technologies 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.datastore.jmx.mbeans.shard;
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;
23 * Maintains a short-lived shared cache of OnDemandShardState.
25 * @author Thomas Pantelis
27 class OnDemandShardStateCache {
28 private static final Cache<String, OnDemandShardState> ONDEMAND_SHARD_STATE_CACHE =
29 CacheBuilder.newBuilder().expireAfterWrite(2, TimeUnit.SECONDS).build();
31 private final ActorRef shardActor;
32 private final String shardName;
33 private volatile String stateRetrievalTime;
35 OnDemandShardStateCache(final String shardName, final ActorRef shardActor) {
36 this.shardName = Preconditions.checkNotNull(shardName);
37 this.shardActor = shardActor;
40 OnDemandShardState get() throws Exception {
41 if (shardActor == null) {
42 return OnDemandShardState.newBuilder().build();
45 return ONDEMAND_SHARD_STATE_CACHE.get(shardName, this::retrieveState);
48 String getStatRetrievaelTime() {
49 return stateRetrievalTime;
52 private OnDemandShardState retrieveState() throws Exception {
53 stateRetrievalTime = null;
54 Timeout timeout = new Timeout(10, TimeUnit.SECONDS);
55 Stopwatch timer = Stopwatch.createStarted();
57 OnDemandShardState state = (OnDemandShardState) Await.result(Patterns.ask(shardActor,
58 GetOnDemandRaftState.INSTANCE, timeout), timeout.duration());
60 stateRetrievalTime = timer.stop().toString();