View Javadoc

1   /**
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  
19  package org.apache.hadoop.metrics2.lib;
20  
21  import org.apache.hadoop.metrics2.MetricsExecutor;
22  
23  import java.util.concurrent.ScheduledExecutorService;
24  import java.util.concurrent.ScheduledThreadPoolExecutor;
25  import java.util.concurrent.ThreadFactory;
26  import java.util.concurrent.atomic.AtomicInteger;
27  
28  /**
29   *  Class to handle the ScheduledExecutorService{@link ScheduledExecutorService} used by MetricMutableQuantiles{@link MetricMutableQuantiles}
30   */
31  public class MetricsExecutorImpl implements MetricsExecutor {
32  
33    @Override
34    public ScheduledExecutorService getExecutor() {
35      return ExecutorSingleton.INSTANCE.scheduler;
36    }
37  
38    @Override
39    public void stop() {
40      if (!getExecutor().isShutdown()) {
41        getExecutor().shutdown();
42      }
43    }
44  
45    private enum ExecutorSingleton {
46      INSTANCE;
47  
48      private final ScheduledExecutorService scheduler = new ScheduledThreadPoolExecutor(1, new ThreadPoolExecutorThreadFactory("HBase-Metrics2-"));
49    }
50  
51    private static class ThreadPoolExecutorThreadFactory implements ThreadFactory {
52      private final String name;
53      private final AtomicInteger threadNumber = new AtomicInteger(1);
54  
55      private ThreadPoolExecutorThreadFactory(String name) {
56        this.name = name;
57      }
58  
59      @Override
60      public Thread newThread(Runnable runnable) {
61        Thread t = new Thread(runnable, name + threadNumber.getAndIncrement());
62        t.setDaemon(true);
63        return t;
64      }
65    }
66  }