Skip to content

feat: Add TokenBucket new algorithm with Junit tests #5840

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Oct 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions DIRECTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,7 @@
* [PriorityQueues](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/queues/PriorityQueues.java)
* [Queue](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/queues/Queue.java)
* [QueueByTwoStacks](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/queues/QueueByTwoStacks.java)
* [TokenBucket](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/queues/TokenBucket.java)
* stacks
* [NodeStack](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/stacks/NodeStack.java)
* [ReverseStack](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/stacks/ReverseStack.java)
Expand Down Expand Up @@ -865,6 +866,7 @@
* [PriorityQueuesTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/queues/PriorityQueuesTest.java)
* [QueueByTwoStacksTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/queues/QueueByTwoStacksTest.java)
* [QueueTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/queues/QueueTest.java)
* [TokenBucketTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/queues/TokenBucketTest.java)
* stacks
* [NodeStackTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/stacks/NodeStackTest.java)
* [StackArrayListTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/stacks/StackArrayListTest.java)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package com.thealgorithms.datastructures.queues;

import java.util.concurrent.TimeUnit;

/**
* TokenBucket implements a token bucket rate limiter algorithm.
* This class is used to control the rate of requests in a distributed system.
* It allows a certain number of requests (tokens) to be processed in a time frame,
* based on the defined refill rate.
*
* Applications: Computer networks, API rate limiting, distributed systems, etc.
*
* @author Hardvan
*/
public final class TokenBucket {
private final int maxTokens;
private final int refillRate; // tokens per second
private int tokens;
private long lastRefill; // Timestamp in nanoseconds

/**
* Constructs a TokenBucket instance.
*
* @param maxTokens Maximum number of tokens the bucket can hold.
* @param refillRate The rate at which tokens are refilled (tokens per second).
*/
public TokenBucket(int maxTokens, int refillRate) {
this.maxTokens = maxTokens;
this.refillRate = refillRate;
this.tokens = maxTokens;
this.lastRefill = System.nanoTime();
}

/**
* Attempts to allow a request based on the available tokens.
* If a token is available, it decrements the token count and allows the request.
* Otherwise, the request is denied.
*
* @return true if the request is allowed, false if the request is denied.
*/
public synchronized boolean allowRequest() {
refillTokens();
if (tokens > 0) {
tokens--;
return true;
}
return false;
}

/**
* Refills the tokens based on the time elapsed since the last refill.
* The number of tokens to be added is calculated based on the elapsed time
* and the refill rate, ensuring the total does not exceed maxTokens.
*/
private void refillTokens() {
long now = System.nanoTime();
long tokensToAdd = (now - lastRefill) / TimeUnit.SECONDS.toNanos(1) * refillRate;
tokens = Math.min(maxTokens, tokens + (int) tokensToAdd);
lastRefill = now;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
package com.thealgorithms.datastructures.queues;

import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

import org.junit.jupiter.api.Test;

public class TokenBucketTest {

@Test
public void testRateLimiter() throws InterruptedException {
TokenBucket bucket = new TokenBucket(5, 1);
for (int i = 0; i < 5; i++) {
assertTrue(bucket.allowRequest());
}
assertFalse(bucket.allowRequest());
Thread.sleep(1000);
assertTrue(bucket.allowRequest());
}

@Test
public void testRateLimiterWithExceedingRequests() throws InterruptedException {
TokenBucket bucket = new TokenBucket(3, 1);

for (int i = 0; i < 3; i++) {
assertTrue(bucket.allowRequest());
}
assertFalse(bucket.allowRequest());

Thread.sleep(1000);
assertTrue(bucket.allowRequest());
assertFalse(bucket.allowRequest());
}

@Test
public void testRateLimiterMultipleRefills() throws InterruptedException {
TokenBucket bucket = new TokenBucket(2, 1);

assertTrue(bucket.allowRequest());
assertTrue(bucket.allowRequest());
assertFalse(bucket.allowRequest());

Thread.sleep(1000);
assertTrue(bucket.allowRequest());

Thread.sleep(1000);
assertTrue(bucket.allowRequest());
assertFalse(bucket.allowRequest());
}

@Test
public void testRateLimiterEmptyBucket() {
TokenBucket bucket = new TokenBucket(0, 1);

assertFalse(bucket.allowRequest());
}

@Test
public void testRateLimiterWithHighRefillRate() throws InterruptedException {
TokenBucket bucket = new TokenBucket(5, 10);

for (int i = 0; i < 5; i++) {
assertTrue(bucket.allowRequest());
}

assertFalse(bucket.allowRequest());

Thread.sleep(1000);

for (int i = 0; i < 5; i++) {
assertTrue(bucket.allowRequest());
}
}

@Test
public void testRateLimiterWithSlowRequests() throws InterruptedException {
TokenBucket bucket = new TokenBucket(5, 1);

for (int i = 0; i < 5; i++) {
assertTrue(bucket.allowRequest());
}

Thread.sleep(1000);
assertTrue(bucket.allowRequest());

Thread.sleep(2000);
assertTrue(bucket.allowRequest());
assertTrue(bucket.allowRequest());
}
}