1 /**
2 * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
3 * agreements. See the NOTICE file distributed with this work for additional information regarding
4 * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the
5 * "License"); you may not use this file except in compliance with the License. You may obtain a
6 * copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable
7 * law or agreed to in writing, software distributed under the License is distributed on an "AS IS"
8 * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License
9 * for the specific language governing permissions and limitations under the License.
10 */
11
12 package org.apache.hadoop.hbase.quotas;
13
14 import java.util.concurrent.TimeUnit;
15
16 import org.apache.hadoop.hbase.classification.InterfaceAudience;
17 import org.apache.hadoop.hbase.classification.InterfaceStability;
18
19 /**
20 * Simple rate limiter. Usage Example: RateLimiter limiter = new RateLimiter(); // At this point you
21 * have a unlimited resource limiter limiter.set(10, TimeUnit.SECONDS); // set 10 resources/sec long
22 * lastTs = 0; // You need to keep track of the last update timestamp while (true) { long now =
23 * System.currentTimeMillis(); // call canExecute before performing resource consuming operation
24 * bool canExecute = limiter.canExecute(now, lastTs); // If there are no available resources, wait
25 * until one is available if (!canExecute) Thread.sleep(limiter.waitInterval()); // ...execute the
26 * work and consume the resource... limiter.consume(); }
27 */
28 @InterfaceAudience.Private
29 @InterfaceStability.Evolving
30 public class RateLimiter {
31 private long tunit = 1000; // Timeunit factor for translating to ms.
32 private long limit = Long.MAX_VALUE; // The max value available resource units can be refilled to.
33 private long avail = Long.MAX_VALUE; // Currently available resource units
34
35 public RateLimiter() {
36 }
37
38 /**
39 * Set the RateLimiter max available resources and refill period.
40 * @param limit The max value available resource units can be refilled to.
41 * @param timeUnit Timeunit factor for translating to ms.
42 */
43 public synchronized void set(final long limit, final TimeUnit timeUnit) {
44 switch (timeUnit) {
45 case NANOSECONDS:
46 throw new RuntimeException("Unsupported NANOSECONDS TimeUnit");
47 case MICROSECONDS:
48 throw new RuntimeException("Unsupported MICROSECONDS TimeUnit");
49 case MILLISECONDS:
50 tunit = 1;
51 break;
52 case SECONDS:
53 tunit = 1000;
54 break;
55 case MINUTES:
56 tunit = 60 * 1000;
57 break;
58 case HOURS:
59 tunit = 60 * 60 * 1000;
60 break;
61 case DAYS:
62 tunit = 24 * 60 * 60 * 1000;
63 break;
64 default:
65 throw new RuntimeException("Invalid TimeUnit " + timeUnit);
66 }
67 this.limit = limit;
68 this.avail = limit;
69 }
70
71 public String toString() {
72 if (limit == Long.MAX_VALUE) {
73 return "RateLimiter(Bypass)";
74 }
75 return "RateLimiter(avail=" + avail + " limit=" + limit + " tunit=" + tunit + ")";
76 }
77
78 /**
79 * Sets the current instance of RateLimiter to a new values. if current limit is smaller than the
80 * new limit, bump up the available resources. Otherwise allow clients to use up the previously
81 * available resources.
82 */
83 public synchronized void update(final RateLimiter other) {
84 this.tunit = other.tunit;
85 if (this.limit < other.limit) {
86 this.avail += (other.limit - this.limit);
87 }
88 this.limit = other.limit;
89 }
90
91 public synchronized boolean isBypass() {
92 return limit == Long.MAX_VALUE;
93 }
94
95 public synchronized long getLimit() {
96 return limit;
97 }
98
99 public synchronized long getAvailable() {
100 return avail;
101 }
102
103 /**
104 * given the time interval, is there at least one resource available to allow execution?
105 * @param now the current timestamp
106 * @param lastTs the timestamp of the last update
107 * @return true if there is at least one resource available, otherwise false
108 */
109 public boolean canExecute(final long now, final long lastTs) {
110 return canExecute(now, lastTs, 1);
111 }
112
113 /**
114 * given the time interval, are there enough available resources to allow execution?
115 * @param now the current timestamp
116 * @param lastTs the timestamp of the last update
117 * @param amount the number of required resources
118 * @return true if there are enough available resources, otherwise false
119 */
120 public synchronized boolean canExecute(final long now, final long lastTs, final long amount) {
121 return avail >= amount ? true : refill(now, lastTs) >= amount;
122 }
123
124 /**
125 * consume one available unit.
126 */
127 public void consume() {
128 consume(1);
129 }
130
131 /**
132 * consume amount available units.
133 * @param amount the number of units to consume
134 */
135 public synchronized void consume(final long amount) {
136 this.avail -= amount;
137 }
138
139 /**
140 * @return estimate of the ms required to wait before being able to provide 1 resource.
141 */
142 public long waitInterval() {
143 return waitInterval(1);
144 }
145
146 /**
147 * @return estimate of the ms required to wait before being able to provide "amount" resources.
148 */
149 public synchronized long waitInterval(final long amount) {
150 // TODO Handle over quota?
151 return (amount <= avail) ? 0 : ((amount * tunit) / limit) - ((avail * tunit) / limit);
152 }
153
154 /**
155 * given the specified time interval, refill the avilable units to the proportionate to elapsed
156 * time or to the prespecified limit.
157 */
158 private long refill(final long now, final long lastTs) {
159 long delta = (limit * (now - lastTs)) / tunit;
160 if (delta > 0) {
161 avail = Math.min(limit, avail + delta);
162 }
163 return avail;
164 }
165 }