Skip to content

Commit

Permalink
* rate: RateControl, replace synchronized with ReentrantLock
Browse files Browse the repository at this point in the history
Signed-off-by: neo <1100909+neowu@users.noreply.github.com>
  • Loading branch information
neowu committed Mar 22, 2024
1 parent f943a5e commit 300dcdb
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 5 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

* mysql: updated and patched to 8.3.0, fixed CJException should be wrapped as SQLException
> make sure use "core.framework.mysql:mysql-connector-j:8.3.0-r2"
* rate: RateControl, replace synchronized with ReentrantLock

### 9.0.8 (1/29/2024 - 3/7/2024)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,24 @@

import java.time.Duration;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

/**
* @author neo
*/
public class RateControl {
private final Logger logger = LoggerFactory.getLogger(RateControl.class);

private final ReentrantLock lock = new ReentrantLock();
private Map<String, RateConfig> config;
private Map<String, Rate> rates;

public void maxEntries(int entries) {
synchronized (this) {
lock.lock();
try {
rates = new LRUMap<>(entries);
} finally {
lock.unlock();
}
}

Expand Down Expand Up @@ -58,8 +63,11 @@ boolean acquire(String group, String clientIP) {

String key = group + "/" + clientIP;
Rate rate;
synchronized (this) {
lock.lock();
try {
rate = rates.computeIfAbsent(key, k -> new Rate(config.maxPermits));
} finally {
lock.unlock();
}
long currentTime = System.nanoTime();
return rate.acquire(currentTime, config.maxPermits, config.fillRatePerNano);
Expand All @@ -69,8 +77,9 @@ record RateConfig(int maxPermits, double fillRatePerNano) {
}

static final class Rate {
volatile double currentPermits;
volatile long lastUpdateTime;
private final ReentrantLock lock = new ReentrantLock();
double currentPermits;
long lastUpdateTime;

Rate(int currentPermits) {
this.currentPermits = currentPermits;
Expand All @@ -79,7 +88,8 @@ static final class Rate {

// under multi-thread condition, the order of acquires are not determined, currentTime can be earlier than lastUpdateTime (e.g. lastUpdateTime was updated by a later acquire first)
boolean acquire(long currentTime, int maxPermits, double fillRatePerNano) {
synchronized (this) {
lock.lock();
try {
long timeElapsed = Math.max(0, currentTime - lastUpdateTime);
currentPermits = Math.min(maxPermits, currentPermits + fillRatePerNano * timeElapsed);
lastUpdateTime = lastUpdateTime + timeElapsed;
Expand All @@ -90,6 +100,8 @@ boolean acquire(long currentTime, int maxPermits, double fillRatePerNano) {
} else {
return false;
}
} finally {
lock.unlock();
}
}
}
Expand Down

0 comments on commit 300dcdb

Please sign in to comment.