View Javadoc

1   /*
2    *
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *     http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   */
19  
20  package org.apache.hadoop.hbase.util;
21  
22  import java.util.Map;
23  import java.util.Set;
24  import java.util.concurrent.ConcurrentHashMap;
25  import org.apache.hadoop.conf.Configuration;
26  import org.apache.hadoop.hbase.HConstants;
27  import org.apache.hadoop.hbase.classification.InterfaceAudience;
28  
29  /**
30   * LossyCounting utility, bounded data structure that maintains approximate high frequency
31   * elements in data stream.
32   *
33   * Bucket size is 1 / error rate.  (Error rate is 0.02 by default)
34   * Lemma If element does not appear in set, then is frequency is less than e * N
35   *       (N is total element counts until now.)
36   * Based on paper:
37   * http://www.vldb.org/conf/2002/S10P03.pdf
38   */
39  @InterfaceAudience.Private
40  public class LossyCounting {
41    private long bucketSize;
42    private int currentTerm;
43    private Map<String, Integer> data;
44    private long totalDataCount;
45    private LossyCountingListener listener;
46  
47    public interface LossyCountingListener {
48      void sweep(String key);
49    }
50  
51    LossyCounting(double errorRate) {
52      this(errorRate, null);
53    }
54  
55    public LossyCounting(double errorRate, LossyCountingListener listener) {
56      if (errorRate < 0.0 || errorRate > 1.0) {
57        throw new IllegalArgumentException(" Lossy Counting error rate should be within range [0,1]");
58      }
59      this.bucketSize = (long) Math.ceil(1 / errorRate);
60      this.currentTerm = 1;
61      this.totalDataCount = 0;
62      this.data = new ConcurrentHashMap<>();
63      this.listener = listener;
64      calculateCurrentTerm();
65    }
66  
67    LossyCounting(Configuration conf) {
68      this(conf, null);
69    }
70  
71    public LossyCounting(Configuration conf, LossyCountingListener listener) {
72      this(conf.getDouble(HConstants.DEFAULT_LOSSY_COUNTING_ERROR_RATE, 0.02), listener);
73    }
74  
75    private void addByOne(String key) {
76      //If entry exists, we update the entry by incrementing its frequency by one. Otherwise,
77      //we create a new entry starting with currentTerm so that it will not be pruned immediately
78      Integer i = data.get(key);
79      if (i == null) {
80        i = currentTerm != 0 ? currentTerm - 1 : 0;
81      }
82      data.put(key, i + 1);
83      //update totalDataCount and term
84      totalDataCount++;
85      calculateCurrentTerm();
86    }
87  
88    public void add(String key) {
89      addByOne(key);
90      if (totalDataCount % bucketSize == 0) {
91        //sweep the entries at bucket boundaries
92        sweep();
93      }
94    }
95  
96    /**
97     * sweep low frequency data
98     * @return Names of elements got swept
99     */
100   private void sweep() {
101     for(Map.Entry<String, Integer> entry : data.entrySet()) {
102       if(entry.getValue() < currentTerm) {
103         String metric = entry.getKey();
104         data.remove(metric);
105         if (listener != null) {
106           listener.sweep(metric);
107         }
108       }
109     }
110   }
111 
112   /**
113    * Calculate and set current term
114    */
115   private void calculateCurrentTerm() {
116     this.currentTerm = (int) Math.ceil(1.0 * totalDataCount / (double) bucketSize);
117   }
118 
119   public long getBucketSize(){
120     return bucketSize;
121   }
122 
123   public long getDataSize() {
124     return data.size();
125   }
126 
127   public boolean contains(String key) {
128     return data.containsKey(key);
129   }
130 
131   public Set<String> getElements(){
132     return data.keySet();
133   }
134 
135   public long getCurrentTerm() {
136     return currentTerm;
137   }
138 }
139