Merge "Bug 1446: Add JMX stats for clustered data store"
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / datastore / jmx / mbeans / shard / ShardMBeanFactory.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 package org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard;
9
10 import java.util.concurrent.Callable;
11 import java.util.concurrent.ExecutionException;
12
13 import org.slf4j.Logger;
14 import org.slf4j.LoggerFactory;
15
16 import com.google.common.cache.Cache;
17 import com.google.common.cache.CacheBuilder;
18
19 /**
20  * @author Basheeruddin syedbahm@cisco.com
21  *
22  */
23 public class ShardMBeanFactory {
24
25     private static final Logger LOG = LoggerFactory.getLogger(ShardMBeanFactory.class);
26
27     private static Cache<String,ShardStats> shardMBeansCache =
28                                       CacheBuilder.newBuilder().weakValues().build();
29
30     public static ShardStats getShardStatsMBean(final String shardName, final String mxBeanType) {
31         final String finalMXBeanType = mxBeanType != null ? mxBeanType : "DistDataStore";
32         try {
33             return shardMBeansCache.get(shardName, new Callable<ShardStats>() {
34                 @Override
35                 public ShardStats call() throws Exception {
36                     ShardStats shardStatsMBeanImpl = new ShardStats(shardName, finalMXBeanType);
37                     shardStatsMBeanImpl.registerMBean();
38                     return shardStatsMBeanImpl;
39                 }
40             });
41         } catch(ExecutionException e) {
42             LOG.error(String.format("Could not create MXBean for shard: %s", shardName), e);
43             // Just return an instance that isn't registered.
44             return new ShardStats(shardName, finalMXBeanType);
45         }
46     }
47 }