001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hbase.metrics.impl;
019
020import java.util.Collection;
021import java.util.Collections;
022import java.util.Optional;
023import java.util.Set;
024import org.apache.hadoop.hbase.metrics.MetricRegistries;
025import org.apache.hadoop.hbase.metrics.MetricRegistry;
026import org.apache.hadoop.hbase.metrics.MetricRegistryFactory;
027import org.apache.hadoop.hbase.metrics.MetricRegistryInfo;
028import org.apache.yetus.audience.InterfaceAudience;
029
030/**
031 * Implementation of MetricRegistries that does ref-counting.
032 */
033@InterfaceAudience.Private
034public class MetricRegistriesImpl extends MetricRegistries {
035  private final MetricRegistryFactory factory;
036  private final RefCountingMap<MetricRegistryInfo, MetricRegistry> registries;
037
038  public MetricRegistriesImpl() {
039    this(new MetricRegistryFactoryImpl());
040  }
041
042  public MetricRegistriesImpl(MetricRegistryFactory factory) {
043    this.factory = factory;
044    this.registries = new RefCountingMap<>();
045  }
046
047  @Override
048  public MetricRegistry create(MetricRegistryInfo info) {
049    return registries.put(info, () -> factory.create(info));
050  }
051
052  @Override
053  public boolean remove(MetricRegistryInfo key) {
054    return registries.remove(key) == null;
055  }
056
057  @Override
058  public Optional<MetricRegistry> get(MetricRegistryInfo info) {
059    return Optional.ofNullable(registries.get(info));
060  }
061
062  @Override
063  public Collection<MetricRegistry> getMetricRegistries() {
064    return Collections.unmodifiableCollection(registries.values());
065  }
066
067  @Override
068  public void clear() {
069    registries.clear();
070  }
071
072  @Override
073  public Set<MetricRegistryInfo> getMetricRegistryInfos() {
074    return Collections.unmodifiableSet(registries.keySet());
075  }
076}