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.metrics2.lib;
019
020import java.util.concurrent.ScheduledExecutorService;
021import java.util.concurrent.ScheduledThreadPoolExecutor;
022import java.util.concurrent.ThreadFactory;
023import java.util.concurrent.atomic.AtomicInteger;
024import org.apache.hadoop.metrics2.MetricsExecutor;
025import org.apache.yetus.audience.InterfaceAudience;
026
027/**
028 * Class to handle the ScheduledExecutorService{@link ScheduledExecutorService} used by
029 * MetricsRegionAggregateSourceImpl, and JmxCacheBuster
030 */
031@InterfaceAudience.Private
032public class MetricsExecutorImpl implements MetricsExecutor {
033
034  @Override
035  public ScheduledExecutorService getExecutor() {
036    return ExecutorSingleton.INSTANCE.scheduler;
037  }
038
039  @Override
040  public void stop() {
041    if (!getExecutor().isShutdown()) {
042      getExecutor().shutdown();
043    }
044  }
045
046  @SuppressWarnings("ImmutableEnumChecker")
047  private enum ExecutorSingleton {
048    INSTANCE;
049
050    private final transient ScheduledExecutorService scheduler =
051      new ScheduledThreadPoolExecutor(1, new ThreadPoolExecutorThreadFactory("HBase-Metrics2-"));
052  }
053
054  private final static class ThreadPoolExecutorThreadFactory implements ThreadFactory {
055    private final String name;
056    private final AtomicInteger threadNumber = new AtomicInteger(1);
057
058    private ThreadPoolExecutorThreadFactory(String name) {
059      this.name = name;
060    }
061
062    @Override
063    public Thread newThread(Runnable runnable) {
064      Thread t = new Thread(runnable, name + threadNumber.getAndIncrement());
065      t.setDaemon(true);
066      return t;
067    }
068  }
069}