├── .gitignore
├── .travis.yml
├── LICENSE
├── README.markdown
├── pom.xml
└── src
├── main
└── java
│ └── org
│ └── isomorphism
│ └── util
│ ├── FixedIntervalRefillStrategy.java
│ ├── TokenBucket.java
│ ├── TokenBucketImpl.java
│ └── TokenBuckets.java
└── test
└── java
└── org
└── isomorphism
└── util
├── FixedIntervalRefillStrategyTest.java
├── TokenBucketBuilderTest.java
└── TokenBucketImplTest.java
/.gitignore:
--------------------------------------------------------------------------------
1 | # IntelliJ Files
2 | .idea/
3 | *.ipr
4 | *.iws
5 | *.iml
6 |
7 | # Eclipse Files
8 | .classpath
9 | .project
10 |
11 | # Build outputs
12 | target/
13 | reports/
14 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: java
2 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | APPENDIX: How to apply the Apache License to your work.
180 |
181 | To apply the Apache License to your work, attach the following
182 | boilerplate notice, with the fields enclosed by brackets "[]"
183 | replaced with your own identifying information. (Don't include
184 | the brackets!) The text should be enclosed in the appropriate
185 | comment syntax for the file format. We also recommend that a
186 | file or class name and description of purpose be included on the
187 | same "printed page" as the copyright notice for easier
188 | identification within third-party archives.
189 |
190 | Copyright [yyyy] [name of copyright owner]
191 |
192 | Licensed under the Apache License, Version 2.0 (the "License");
193 | you may not use this file except in compliance with the License.
194 | You may obtain a copy of the License at
195 |
196 | http://www.apache.org/licenses/LICENSE-2.0
197 |
198 | Unless required by applicable law or agreed to in writing, software
199 | distributed under the License is distributed on an "AS IS" BASIS,
200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 | See the License for the specific language governing permissions and
202 | limitations under the License.
203 |
--------------------------------------------------------------------------------
/README.markdown:
--------------------------------------------------------------------------------
1 | Introduction
2 | ------------
3 | This library provides an implementation of a token bucket algorithm which is useful for providing rate limited access
4 | to a portion of code. The implementation provided is that of a "leaky bucket" in the sense that the bucket has a finite
5 | capacity and any added tokens that would exceed this capacity will "overflow" out of the bucket and be lost forever.
6 |
7 | In this implementation the rules for refilling the bucket are encapsulated in a provided RefillStrategy instance. Prior
8 | to attempting to consume any tokens the refill strategy will be consulted to see how many tokens should be added to the
9 | bucket
10 |
11 | We use [Travis CI](http://about.travis-ci.org) for build verification. [](http://travis-ci.org/bbeck/token-bucket)
12 |
13 | See also:
14 |
15 | * [Wikipedia - Token Bucket](http://en.wikipedia.org/wiki/Token_bucket)
16 | * [Wikipedia - Leaky Bucket](http://en.wikipedia.org/wiki/Leaky_bucket)
17 |
18 | Usage
19 | -----
20 | Using a token bucket is incredibly easy and is best illustrated by an example. Suppose you have a piece of code that
21 | polls a website and you would only like to be able to access the site once per second:
22 |
23 | ```java
24 | // Create a token bucket with a capacity of 1 token that refills at a fixed interval of 1 token/sec.
25 | TokenBucket bucket = TokenBuckets.builder()
26 | .withCapacity(1)
27 | .withFixedIntervalRefillStrategy(1, 1, TimeUnit.SECONDS)
28 | .build();
29 |
30 | // ...
31 |
32 | while (true) {
33 | // Consume a token from the token bucket. If a token is not available this method will block until
34 | // the refill strategy adds one to the bucket.
35 | bucket.consume(1);
36 |
37 | poll();
38 | }
39 | ```
40 |
41 | As another example suppose you wanted to rate limit the size response of a server to the client to 20 kb/sec but want to
42 | allow for a periodic burst rate of 40 kb/sec:
43 |
44 | ```java
45 | // Create a token bucket with a capacity of 40 kb tokens that refills at a fixed interval of 20 kb tokens per second
46 | TokenBucket bucket = TokenBuckets.builder()
47 | .withCapacity(40960)
48 | .withFixedIntervalRefillStrategy(20480, 1, TimeUnit.SECONDS)
49 | .build();
50 |
51 | // ...
52 |
53 | while (true) {
54 | String response = prepareResponse();
55 |
56 | // Consume tokens from the bucket commensurate with the size of the response
57 | bucket.consume(response.length());
58 |
59 | send(response);
60 | }
61 | ```
62 |
63 | Maven Setup
64 | -----------
65 | The token bucket library is distributed through maven central. Just include it as a dependency in your ```pom.xml```.
66 |
67 | ```xml
68 |
69 | org.isomorphism
70 | token-bucket
71 | 1.6
72 |
73 | ```
74 |
75 | License
76 | -------
77 | Copyright 2012-2015 Brandon Beck
78 | Licensed under the Apache Software License, Version 2.0: .
79 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 4.0.0
4 |
5 | org.isomorphism
6 | token-bucket
7 | 1.8-SNAPSHOT
8 | jar
9 |
10 |
11 | org.sonatype.oss
12 | oss-parent
13 | 9
14 |
15 |
16 | token-bucket
17 | Token bucket algorithm for rate-limiting
18 | http://github.com/bbeck/token-bucket
19 |
20 |
21 | The Apache Software License, Version 2.0
22 | http://www.apache.org/licenses/LICENSE-2.0
23 | repo
24 |
25 |
26 |
27 |
28 | UTF-8
29 | UTF-8
30 |
31 |
32 |
33 | http://github.com/bbeck/token-bucket
34 | scm:git:git@github.com:bbeck/token-bucket.git
35 | scm:git:git@github.com:bbeck/token-bucket.git
36 | HEAD
37 |
38 |
39 |
40 |
41 |
42 |
43 | org.apache.maven.plugins
44 | maven-release-plugin
45 | 2.5.1
46 |
47 | v@{project.version}
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 | bbeck
56 | Brandon Beck
57 | http://github.com/bbeck
58 |
59 |
60 |
61 |
62 |
63 | com.google.guava
64 | guava
65 | 18.0
66 |
67 |
68 |
69 | junit
70 | junit
71 | 4.12
72 | test
73 |
74 |
75 |
76 | org.mockito
77 | mockito-core
78 | 1.10.19
79 | test
80 |
81 |
82 |
83 |
--------------------------------------------------------------------------------
/src/main/java/org/isomorphism/util/FixedIntervalRefillStrategy.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012-2014 Brandon Beck
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package org.isomorphism.util;
17 |
18 | import com.google.common.base.Ticker;
19 |
20 | import java.util.concurrent.TimeUnit;
21 |
22 | /**
23 | * A token bucket refill strategy that will provide N tokens for a token bucket to consume every T units of time.
24 | * The tokens are refilled in bursts rather than at a fixed rate. This refill strategy will never allow more than
25 | * N tokens to be consumed during a window of time T.
26 | */
27 | public class FixedIntervalRefillStrategy implements TokenBucketImpl.RefillStrategy
28 | {
29 | private final Ticker ticker;
30 | private final long numTokensPerPeriod;
31 | private final long periodDurationInNanos;
32 | private long lastRefillTime;
33 | private long nextRefillTime;
34 |
35 | /**
36 | * Create a FixedIntervalRefillStrategy.
37 | *
38 | * @param ticker A ticker to use to measure time.
39 | * @param numTokensPerPeriod The number of tokens to add to the bucket every period.
40 | * @param period How often to refill the bucket.
41 | * @param unit Unit for period.
42 | */
43 | public FixedIntervalRefillStrategy(Ticker ticker, long numTokensPerPeriod, long period, TimeUnit unit)
44 | {
45 | this.ticker = ticker;
46 | this.numTokensPerPeriod = numTokensPerPeriod;
47 | this.periodDurationInNanos = unit.toNanos(period);
48 | this.lastRefillTime = -periodDurationInNanos;
49 | this.nextRefillTime = -periodDurationInNanos;
50 | }
51 |
52 | @Override
53 | public synchronized long refill()
54 | {
55 | long now = ticker.read();
56 | if (now < nextRefillTime) {
57 | return 0;
58 | }
59 |
60 | // We now know that we need to refill the bucket with some tokens, the question is how many. We need to count how
61 | // many periods worth of tokens we've missed.
62 | long numPeriods = Math.max(0, (now - lastRefillTime) / periodDurationInNanos);
63 |
64 | // Move the last refill time forward by this many periods.
65 | lastRefillTime += numPeriods * periodDurationInNanos;
66 |
67 | // ...and we'll refill again one period after the last time we refilled.
68 | nextRefillTime = lastRefillTime + periodDurationInNanos;
69 |
70 | return numPeriods * numTokensPerPeriod;
71 | }
72 |
73 | @Override
74 | public long getDurationUntilNextRefill(TimeUnit unit)
75 | {
76 | long now = ticker.read();
77 | return unit.convert(Math.max(0, nextRefillTime - now), TimeUnit.NANOSECONDS);
78 | }
79 | }
80 |
81 |
--------------------------------------------------------------------------------
/src/main/java/org/isomorphism/util/TokenBucket.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012-2014 Brandon Beck
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package org.isomorphism.util;
17 |
18 | import java.util.concurrent.TimeUnit;
19 |
20 | /**
21 | * A token bucket is used for rate limiting access to a portion of code.
22 | *
23 | * @see Token Bucket on Wikipedia
24 | * @see Leaky Bucket on Wikipedia
25 | */
26 | public interface TokenBucket
27 | {
28 | /**
29 | * Returns the capacity of this token bucket. This is the maximum number of tokens that the bucket can hold at
30 | * any one time.
31 | *
32 | * @return The capacity of the bucket.
33 | */
34 | long getCapacity();
35 |
36 | /**
37 | * Returns the current number of tokens in the bucket. If the bucket is empty then this method will return 0.
38 | *
39 | * @return The current number of tokens in the bucket.
40 | */
41 | long getNumTokens();
42 |
43 | /**
44 | * Returns the amount of time in the specified time unit until the next group of tokens can be added to the token
45 | * bucket.
46 | *
47 | * @see org.isomorphism.util.TokenBucket.RefillStrategy#getDurationUntilNextRefill(java.util.concurrent.TimeUnit)
48 | * @param unit The time unit to express the return value in.
49 | * @return The amount of time until the next group of tokens can be added to the token bucket.
50 | */
51 | long getDurationUntilNextRefill(TimeUnit unit) throws UnsupportedOperationException;
52 |
53 | /**
54 | * Attempt to consume a single token from the bucket. If it was consumed then {@code true} is returned, otherwise
55 | * {@code false} is returned.
56 | *
57 | * @return {@code true} if a token was consumed, {@code false} otherwise.
58 | */
59 | boolean tryConsume();
60 |
61 | /**
62 | * Attempt to consume a specified number of tokens from the bucket. If the tokens were consumed then {@code true}
63 | * is returned, otherwise {@code false} is returned.
64 | *
65 | * @param numTokens The number of tokens to consume from the bucket, must be a positive number.
66 | * @return {@code true} if the tokens were consumed, {@code false} otherwise.
67 | */
68 | boolean tryConsume(long numTokens);
69 |
70 | /**
71 | * Consume a single token from the bucket. If no token is currently available then this method will block until a
72 | * token becomes available.
73 | */
74 | void consume();
75 |
76 | /**
77 | * Consumes multiple tokens from the bucket. If enough tokens are not currently available then this method will block
78 | * until
79 | *
80 | * @param numTokens The number of tokens to consume from teh bucket, must be a positive number.
81 | */
82 | void consume(long numTokens);
83 |
84 | /**
85 | * Refills the bucket with the specified number of tokens. If the bucket is currently full or near capacity then
86 | * fewer than {@code numTokens} may be added.
87 | *
88 | * @param numTokens The number of tokens to add to the bucket.
89 | */
90 | void refill(long numTokens);
91 |
92 | /** Encapsulation of a refilling strategy for a token bucket. */
93 | static interface RefillStrategy
94 | {
95 | /**
96 | * Returns the number of tokens to add to the token bucket.
97 | *
98 | * @return The number of tokens to add to the token bucket.
99 | */
100 | long refill();
101 |
102 | /**
103 | * Returns the amount of time in the specified time unit until the next group of tokens can be added to the token
104 | * bucket. Please note, depending on the {@code SleepStrategy} used by the token bucket, tokens may not actually
105 | * be added until much after the returned duration. If for some reason the implementation of
106 | * {@code RefillStrategy} doesn't support knowing when the next batch of tokens will be added, then an
107 | * {@code UnsupportedOperationException} may be thrown. Lastly, if the duration until the next time tokens will
108 | * be added to the token bucket is less than a single unit of the passed in time unit then this method will
109 | * return 0.
110 | *
111 | * @param unit The time unit to express the return value in.
112 | * @return The amount of time until the next group of tokens can be added to the token bucket.
113 | */
114 | long getDurationUntilNextRefill(TimeUnit unit) throws UnsupportedOperationException;
115 | }
116 |
117 | /** Encapsulation of a strategy for relinquishing control of the CPU. */
118 | static interface SleepStrategy
119 | {
120 | /**
121 | * Sleep for a short period of time to allow other threads and system processes to execute.
122 | */
123 | void sleep();
124 | }
125 | }
126 |
--------------------------------------------------------------------------------
/src/main/java/org/isomorphism/util/TokenBucketImpl.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012-2014 Brandon Beck
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package org.isomorphism.util;
17 |
18 | import java.util.concurrent.TimeUnit;
19 |
20 | import static com.google.common.base.Preconditions.checkArgument;
21 | import static com.google.common.base.Preconditions.checkNotNull;
22 |
23 | /**
24 | * A token bucket implementation that is of a leaky bucket in the sense that it has a finite capacity and any added
25 | * tokens that would exceed this capacity will "overflow" out of the bucket and are lost forever.
26 | *
27 | * In this implementation the rules for refilling the bucket are encapsulated in a provided {@code RefillStrategy}
28 | * instance. Prior to attempting to consume any tokens the refill strategy will be consulted to see how many tokens
29 | * should be added to the bucket.
30 | *
31 | * In addition in this implementation the method of yielding CPU control is encapsulated in the provided
32 | * {@code SleepStrategy} instance. For high performance applications where tokens are being refilled incredibly quickly
33 | * and an accurate bucket implementation is required, it may be useful to never yield control of the CPU and to instead
34 | * busy wait. This strategy allows the caller to make this decision for themselves instead of the library forcing a
35 | * decision.
36 | */
37 | class TokenBucketImpl implements TokenBucket
38 | {
39 | private final long capacity;
40 | private final RefillStrategy refillStrategy;
41 | private final SleepStrategy sleepStrategy;
42 | private long size;
43 |
44 | TokenBucketImpl(long capacity, long initialTokens, RefillStrategy refillStrategy, SleepStrategy sleepStrategy)
45 | {
46 | checkArgument(capacity > 0);
47 | checkArgument(initialTokens <= capacity);
48 |
49 | this.capacity = capacity;
50 | this.refillStrategy = checkNotNull(refillStrategy);
51 | this.sleepStrategy = checkNotNull(sleepStrategy);
52 | this.size = initialTokens;
53 | }
54 |
55 | /**
56 | * Returns the capacity of this token bucket. This is the maximum number of tokens that the bucket can hold at
57 | * any one time.
58 | *
59 | * @return The capacity of the bucket.
60 | */
61 | @Override
62 | public long getCapacity()
63 | {
64 | return capacity;
65 | }
66 |
67 | /**
68 | * Returns the current number of tokens in the bucket. If the bucket is empty then this method will return 0.
69 | *
70 | * @return The current number of tokens in the bucket.
71 | */
72 | @Override
73 | public synchronized long getNumTokens()
74 | {
75 | // Give the refill strategy a chance to add tokens if it needs to so that we have an accurate
76 | // count.
77 | refill(refillStrategy.refill());
78 |
79 | return size;
80 | }
81 |
82 | /**
83 | * Returns the amount of time in the specified time unit until the next group of tokens can be added to the token
84 | * bucket.
85 | *
86 | * @see org.isomorphism.util.TokenBucket.RefillStrategy#getDurationUntilNextRefill(java.util.concurrent.TimeUnit)
87 | * @param unit The time unit to express the return value in.
88 | * @return The amount of time until the next group of tokens can be added to the token bucket.
89 | */
90 | @Override
91 | public long getDurationUntilNextRefill(TimeUnit unit) throws UnsupportedOperationException
92 | {
93 | return refillStrategy.getDurationUntilNextRefill(unit);
94 | }
95 |
96 | /**
97 | * Attempt to consume a single token from the bucket. If it was consumed then {@code true} is returned, otherwise
98 | * {@code false} is returned.
99 | *
100 | * @return {@code true} if a token was consumed, {@code false} otherwise.
101 | */
102 | public boolean tryConsume()
103 | {
104 | return tryConsume(1);
105 | }
106 |
107 | /**
108 | * Attempt to consume a specified number of tokens from the bucket. If the tokens were consumed then {@code true}
109 | * is returned, otherwise {@code false} is returned.
110 | *
111 | * @param numTokens The number of tokens to consume from the bucket, must be a positive number.
112 | * @return {@code true} if the tokens were consumed, {@code false} otherwise.
113 | */
114 | public synchronized boolean tryConsume(long numTokens)
115 | {
116 | checkArgument(numTokens > 0, "Number of tokens to consume must be positive");
117 | checkArgument(numTokens <= capacity, "Number of tokens to consume must be less than the capacity of the bucket.");
118 |
119 | refill(refillStrategy.refill());
120 |
121 | // Now try to consume some tokens
122 | if (numTokens <= size) {
123 | size -= numTokens;
124 | return true;
125 | }
126 |
127 | return false;
128 | }
129 |
130 | /**
131 | * Consume a single token from the bucket. If no token is currently available then this method will block until a
132 | * token becomes available.
133 | */
134 | public void consume()
135 | {
136 | consume(1);
137 | }
138 |
139 | /**
140 | * Consumes multiple tokens from the bucket. If enough tokens are not currently available then this method will block
141 | * until
142 | *
143 | * @param numTokens The number of tokens to consume from teh bucket, must be a positive number.
144 | */
145 | public void consume(long numTokens)
146 | {
147 | while (true) {
148 | if (tryConsume(numTokens)) {
149 | break;
150 | }
151 |
152 | sleepStrategy.sleep();
153 | }
154 | }
155 |
156 | /**
157 | * Refills the bucket with the specified number of tokens. If the bucket is currently full or near capacity then
158 | * fewer than {@code numTokens} may be added.
159 | *
160 | * @param numTokens The number of tokens to add to the bucket.
161 | */
162 | public synchronized void refill(long numTokens)
163 | {
164 | long newTokens = Math.min(capacity, Math.max(0, numTokens));
165 | size = Math.max(0, Math.min(size + newTokens, capacity));
166 | }
167 | }
168 |
--------------------------------------------------------------------------------
/src/main/java/org/isomorphism/util/TokenBuckets.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012-2014 Brandon Beck
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package org.isomorphism.util;
17 |
18 | import com.google.common.base.Ticker;
19 | import com.google.common.util.concurrent.Uninterruptibles;
20 |
21 | import java.util.concurrent.TimeUnit;
22 |
23 | import static com.google.common.base.Preconditions.checkArgument;
24 | import static com.google.common.base.Preconditions.checkNotNull;
25 |
26 | /** Static utility methods pertaining to creating {@link TokenBucketImpl} instances. */
27 | public final class TokenBuckets
28 | {
29 | private TokenBuckets() {}
30 |
31 | /** Create a new builder for token buckets. */
32 | public static Builder builder()
33 | {
34 | return new Builder();
35 | }
36 |
37 | public static class Builder
38 | {
39 | private Long capacity = null;
40 | private long initialTokens = 0;
41 | private TokenBucketImpl.RefillStrategy refillStrategy = null;
42 | private TokenBucketImpl.SleepStrategy sleepStrategy = YIELDING_SLEEP_STRATEGY;
43 | private final Ticker ticker = Ticker.systemTicker();
44 |
45 | /** Specify the overall capacity of the token bucket. */
46 | public Builder withCapacity(long numTokens)
47 | {
48 | checkArgument(numTokens > 0, "Must specify a positive number of tokens");
49 | capacity = numTokens;
50 | return this;
51 | }
52 |
53 | /** Initialize the token bucket with a specific number of tokens. */
54 | public Builder withInitialTokens(long numTokens)
55 | {
56 | checkArgument(numTokens > 0, "Must specify a positive number of tokens");
57 | initialTokens = numTokens;
58 | return this;
59 | }
60 |
61 | /** Refill tokens at a fixed interval. */
62 | public Builder withFixedIntervalRefillStrategy(long refillTokens, long period, TimeUnit unit)
63 | {
64 | return withRefillStrategy(new FixedIntervalRefillStrategy(ticker, refillTokens, period, unit));
65 | }
66 |
67 | /** Use a user defined refill strategy. */
68 | public Builder withRefillStrategy(TokenBucket.RefillStrategy refillStrategy)
69 | {
70 | this.refillStrategy = checkNotNull(refillStrategy);
71 | return this;
72 | }
73 |
74 | /** Use a sleep strategy that will always attempt to yield the CPU to other processes. */
75 | public Builder withYieldingSleepStrategy()
76 | {
77 | return withSleepStrategy(YIELDING_SLEEP_STRATEGY);
78 | }
79 |
80 | /**
81 | * Use a sleep strategy that will not yield the CPU to other processes. It will busy wait until more tokens become
82 | * available.
83 | */
84 | public Builder withBusyWaitSleepStrategy()
85 | {
86 | return withSleepStrategy(BUSY_WAIT_SLEEP_STRATEGY);
87 | }
88 |
89 | /** Use a user defined sleep strategy. */
90 | public Builder withSleepStrategy(TokenBucket.SleepStrategy sleepStrategy)
91 | {
92 | this.sleepStrategy = checkNotNull(sleepStrategy);
93 | return this;
94 | }
95 |
96 | /** Build the token bucket. */
97 | public TokenBucket build()
98 | {
99 | checkNotNull(capacity, "Must specify a capacity");
100 | checkNotNull(refillStrategy, "Must specify a refill strategy");
101 |
102 | return new TokenBucketImpl(capacity, initialTokens, refillStrategy, sleepStrategy);
103 | }
104 | }
105 |
106 | private static final TokenBucketImpl.SleepStrategy YIELDING_SLEEP_STRATEGY = new TokenBucketImpl.SleepStrategy()
107 | {
108 | @Override
109 | public void sleep()
110 | {
111 | // Sleep for the smallest unit of time possible just to relinquish control
112 | // and to allow other threads to run.
113 | Uninterruptibles.sleepUninterruptibly(1, TimeUnit.NANOSECONDS);
114 | }
115 | };
116 |
117 | private static final TokenBucketImpl.SleepStrategy BUSY_WAIT_SLEEP_STRATEGY = new TokenBucketImpl.SleepStrategy()
118 | {
119 | @Override
120 | public void sleep()
121 | {
122 | // Do nothing, don't sleep.
123 | }
124 | };
125 | }
126 |
--------------------------------------------------------------------------------
/src/test/java/org/isomorphism/util/FixedIntervalRefillStrategyTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012-2014 Brandon Beck
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package org.isomorphism.util;
17 |
18 | import com.google.common.base.Ticker;
19 | import org.junit.Test;
20 |
21 | import java.util.concurrent.TimeUnit;
22 |
23 | import static org.junit.Assert.assertEquals;
24 |
25 | public class FixedIntervalRefillStrategyTest
26 | {
27 | private static final long N = 5; // 5 tokens
28 | private static final long P = 10; // every 10
29 | private static final TimeUnit U = TimeUnit.SECONDS; // seconds
30 |
31 | private final MockTicker ticker = new MockTicker();
32 | private final FixedIntervalRefillStrategy strategy = new FixedIntervalRefillStrategy(ticker, N, P, U);
33 |
34 | @Test
35 | public void testFirstRefill()
36 | {
37 | assertEquals(N, strategy.refill());
38 | }
39 |
40 | @Test
41 | public void testNoRefillUntilPeriodUp()
42 | {
43 | strategy.refill();
44 |
45 | // Another refill shouldn't come for P time units.
46 | for (int i = 0; i < P - 1; i++) {
47 | ticker.advance(1, U);
48 | assertEquals(0, strategy.refill());
49 | }
50 | }
51 |
52 | @Test
53 | public void testRefillEveryPeriod()
54 | {
55 | strategy.refill();
56 |
57 | ticker.advance(P, U);
58 | assertEquals(N, strategy.refill());
59 |
60 | ticker.advance(P, U);
61 | assertEquals(N, strategy.refill());
62 |
63 | ticker.advance(P, U);
64 | assertEquals(N, strategy.refill());
65 | }
66 |
67 | @Test
68 | public void testRefillEveryOtherPeriod()
69 | {
70 | strategy.refill();
71 |
72 | // Move time forward two periods, since we're skipping a period next time we should add double the tokens.
73 | ticker.advance(2 * P, U);
74 | assertEquals(2 * N, strategy.refill());
75 |
76 | ticker.advance(2 * P, U);
77 | assertEquals(2 * N, strategy.refill());
78 | }
79 |
80 | @Test
81 | public void testRefillOnNonEvenPeriods()
82 | {
83 | // The strategy is configured to refill tokens every P time units. So we should only get refills at 0, P, 2P, 3P,
84 | // etc. Any other time should return 0 tokens.
85 |
86 | // t = 0
87 | assertEquals(N, strategy.refill());
88 |
89 | // t = P+1
90 | ticker.advance(P + 1, U);
91 | assertEquals(N, strategy.refill());
92 |
93 | // t = 2P+1
94 | ticker.advance(P, U);
95 | assertEquals(N, strategy.refill());
96 |
97 | // t = 3P
98 | ticker.advance(P - 1, U);
99 | assertEquals(N, strategy.refill());
100 |
101 | // t = 4P-1
102 | ticker.advance(P - 1, U);
103 | assertEquals(0, strategy.refill());
104 |
105 | // t = 4P
106 | ticker.advance(1, U);
107 | assertEquals(N, strategy.refill());
108 | }
109 |
110 | @Test
111 | public void testDurationUntilFirstRefill()
112 | {
113 | // A refill has never happened, so one is supposed to happen immediately.
114 | assertEquals(0, strategy.getDurationUntilNextRefill(TimeUnit.SECONDS));
115 | }
116 |
117 | @Test
118 | public void testDurationAfterFirstRefill()
119 | {
120 | strategy.refill();
121 |
122 | for (int i = 0; i < P - 1; i++) {
123 | assertEquals(P - i, strategy.getDurationUntilNextRefill(TimeUnit.SECONDS));
124 | ticker.advance(1, U);
125 | }
126 | }
127 |
128 | @Test
129 | public void testDurationAtSecondRefillTime()
130 | {
131 | strategy.refill();
132 | ticker.advance(P, U);
133 |
134 | assertEquals(0, strategy.getDurationUntilNextRefill(TimeUnit.SECONDS));
135 | }
136 |
137 | @Test
138 | public void testDurationInProperUnits()
139 | {
140 | strategy.refill();
141 |
142 | assertEquals(10000, strategy.getDurationUntilNextRefill(TimeUnit.MILLISECONDS));
143 | }
144 |
145 | private static final class MockTicker extends Ticker
146 | {
147 | private long now = 0;
148 |
149 | @Override
150 | public long read()
151 | {
152 | return now;
153 | }
154 |
155 | public void advance(long delta, TimeUnit unit)
156 | {
157 | now += unit.toNanos(delta);
158 | }
159 | }
160 | }
161 |
--------------------------------------------------------------------------------
/src/test/java/org/isomorphism/util/TokenBucketBuilderTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012-2014 Brandon Beck
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package org.isomorphism.util;
17 |
18 | import org.junit.Test;
19 |
20 | public class TokenBucketBuilderTest
21 | {
22 | private final TokenBuckets.Builder builder = TokenBuckets.builder();
23 |
24 | @Test(expected = IllegalArgumentException.class)
25 | public void testNegativeCapacity() {
26 | builder.withCapacity(-1);
27 | }
28 |
29 | @Test(expected = IllegalArgumentException.class)
30 | public void testZeroCapacity() {
31 | builder.withCapacity(0);
32 | }
33 |
34 | @Test(expected = IllegalArgumentException.class)
35 | public void testNegativeInitialTokens() {
36 | builder.withInitialTokens(-1);
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/test/java/org/isomorphism/util/TokenBucketImplTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012-2014 Brandon Beck
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package org.isomorphism.util;
17 |
18 | import org.junit.Test;
19 |
20 | import java.util.concurrent.TimeUnit;
21 |
22 | import static org.junit.Assert.assertEquals;
23 | import static org.junit.Assert.assertFalse;
24 | import static org.junit.Assert.assertTrue;
25 | import static org.mockito.Mockito.mock;
26 |
27 | public class TokenBucketImplTest
28 | {
29 | private static final long CAPACITY = 10;
30 |
31 | private final MockRefillStrategy refillStrategy = new MockRefillStrategy();
32 | private final TokenBucket.SleepStrategy sleepStrategy = mock(TokenBucket.SleepStrategy.class);
33 | private final TokenBucketImpl bucket = new TokenBucketImpl(CAPACITY, 0, refillStrategy, sleepStrategy);
34 |
35 | @Test(expected = IllegalArgumentException.class)
36 | public void testNegativeCapacity()
37 | {
38 | new TokenBucketImpl(-1, 0, refillStrategy, sleepStrategy);
39 | }
40 |
41 | @Test(expected = IllegalArgumentException.class)
42 | public void testZeroCapacity()
43 | {
44 | new TokenBucketImpl(0, 0, refillStrategy, sleepStrategy);
45 | }
46 |
47 | @Test(expected = IllegalArgumentException.class)
48 | public void testMoreInitialTokensThanCapacity()
49 | {
50 | new TokenBucketImpl(1, 2, refillStrategy, sleepStrategy);
51 | }
52 |
53 | @Test
54 | public void testGetCapacity()
55 | {
56 | assertEquals(CAPACITY, bucket.getCapacity());
57 | }
58 |
59 | @Test
60 | public void testEmptyBucketHasZeroTokens()
61 | {
62 | assertEquals(0, bucket.getNumTokens());
63 | }
64 |
65 | @Test
66 | public void testBucketWithInitialTokens()
67 | {
68 | TokenBucketImpl bucket = new TokenBucketImpl(CAPACITY, CAPACITY, refillStrategy, sleepStrategy);
69 | assertEquals(CAPACITY, bucket.getNumTokens());
70 | }
71 |
72 | @Test
73 | public void testAddingTokenIncreasesNumTokens()
74 | {
75 | refillStrategy.addToken();
76 | assertEquals(1, bucket.getNumTokens());
77 | }
78 |
79 | @Test
80 | public void testAddingMultipleTokensIncreasesNumTokens()
81 | {
82 | refillStrategy.addTokens(2);
83 | assertEquals(2, bucket.getNumTokens());
84 | }
85 |
86 | @Test
87 | public void testAtCapacityNumTokens()
88 | {
89 | refillStrategy.addTokens(CAPACITY);
90 | assertEquals(CAPACITY, bucket.getNumTokens());
91 | }
92 |
93 | @Test
94 | public void testOverCapacityNumTokens()
95 | {
96 | refillStrategy.addTokens(CAPACITY + 1);
97 | assertEquals(CAPACITY, bucket.getNumTokens());
98 | }
99 |
100 | @Test
101 | public void testConsumingTokenDecreasesNumTokens()
102 | {
103 | refillStrategy.addTokens(1);
104 | bucket.consume();
105 | assertEquals(0, bucket.getNumTokens());
106 | }
107 |
108 | @Test
109 | public void testConsumingMultipleTokensDecreasesNumTokens()
110 | {
111 | refillStrategy.addTokens(CAPACITY);
112 | bucket.consume(2);
113 | assertEquals(CAPACITY - 2, bucket.getNumTokens());
114 | }
115 |
116 | @Test
117 | public void testEmptyNumTokens()
118 | {
119 | refillStrategy.addTokens(CAPACITY);
120 | bucket.consume(CAPACITY);
121 | assertEquals(0, bucket.getNumTokens());
122 | }
123 |
124 | @Test
125 | public void testFailedConsumeKeepsNumTokens()
126 | {
127 | refillStrategy.addTokens(1);
128 | bucket.tryConsume(2);
129 | assertEquals(1, bucket.getNumTokens());
130 | }
131 |
132 | @Test(expected = IllegalArgumentException.class)
133 | public void testTryConsumeZeroTokens()
134 | {
135 | bucket.tryConsume(0);
136 | }
137 |
138 | @Test(expected = IllegalArgumentException.class)
139 | public void testTryConsumeNegativeTokens()
140 | {
141 | bucket.tryConsume(-1);
142 | }
143 |
144 | @Test(expected = IllegalArgumentException.class)
145 | public void testTryConsumeMoreThanCapacityTokens()
146 | {
147 | bucket.tryConsume(100);
148 | }
149 |
150 | @Test
151 | public void testTryConsumeOnEmptyBucket()
152 | {
153 | assertFalse(bucket.tryConsume());
154 | }
155 |
156 | @Test
157 | public void testTryConsumeOneToken()
158 | {
159 | refillStrategy.addToken();
160 | assertTrue(bucket.tryConsume());
161 | }
162 |
163 | @Test
164 | public void testTryConsumeMoreTokensThanAreAvailable()
165 | {
166 | refillStrategy.addToken();
167 | assertFalse(bucket.tryConsume(2));
168 | }
169 |
170 | @Test
171 | public void testTryManuallyRefillOneToken()
172 | {
173 | bucket.refill(1);
174 | assertTrue(bucket.tryConsume());
175 | }
176 |
177 | @Test
178 | public void testTryManuallyRefillCapacityTokens()
179 | {
180 | bucket.refill(CAPACITY);
181 | assertTrue(bucket.tryConsume(CAPACITY));
182 | assertFalse(bucket.tryConsume(1));
183 | }
184 |
185 | @Test
186 | public void testTryManuallyRefillMoreThanCapacityTokens()
187 | {
188 | bucket.refill(CAPACITY + 1);
189 | assertTrue(bucket.tryConsume(CAPACITY));
190 | assertFalse(bucket.tryConsume(1));
191 | }
192 |
193 | @Test
194 | public void testTryManualRefillAndStrategyRefill() {
195 | bucket.refill(CAPACITY);
196 | refillStrategy.addTokens(CAPACITY);
197 | assertTrue(bucket.tryConsume(CAPACITY));
198 | assertFalse(bucket.tryConsume(1));
199 | }
200 |
201 | @Test
202 | public void testTryRefillMoreThanCapacityTokens()
203 | {
204 | refillStrategy.addTokens(CAPACITY + 1);
205 | assertTrue(bucket.tryConsume(CAPACITY));
206 | assertFalse(bucket.tryConsume(1));
207 | }
208 |
209 | @Test
210 | public void testTryRefillWithTooManyTokens()
211 | {
212 | refillStrategy.addTokens(CAPACITY);
213 | assertTrue(bucket.tryConsume());
214 |
215 | refillStrategy.addTokens(Long.MAX_VALUE);
216 | assertTrue(bucket.tryConsume(CAPACITY));
217 | assertFalse(bucket.tryConsume(1));
218 | }
219 |
220 | private static final class MockRefillStrategy implements TokenBucketImpl.RefillStrategy
221 | {
222 | private long numTokensToAdd = 0;
223 |
224 | public long refill()
225 | {
226 | long numTokens = numTokensToAdd;
227 | numTokensToAdd = 0;
228 | return numTokens;
229 | }
230 |
231 | @Override
232 | public long getDurationUntilNextRefill(TimeUnit unit) throws UnsupportedOperationException
233 | {
234 | throw new UnsupportedOperationException();
235 | }
236 |
237 | public void addToken()
238 | {
239 | numTokensToAdd++;
240 | }
241 |
242 | public void addTokens(long numTokens)
243 | {
244 | numTokensToAdd += numTokens;
245 | }
246 | }
247 | }
248 |
--------------------------------------------------------------------------------