Skip to content
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

optimize DefaultTpsLimiter #3654

Merged
merged 4 commits into from
Mar 19, 2019
Merged
Show file tree
Hide file tree
Changes from 2 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
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,13 @@ public boolean isAllowable(URL url, Invocation invocation) {
stats.putIfAbsent(serviceKey,
new StatItem(serviceKey, rate, interval));
statItem = stats.get(serviceKey);
} else {
//rate has changed, rebuild
if (statItem.getRate() != rate) {
stats.put(serviceKey,
new StatItem(serviceKey, rate, interval));
statItem = stats.get(serviceKey);
}
}
return statItem.isAllowable();
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
*/
package org.apache.dubbo.rpc.filter.tps;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.LongAdder;

/**
* Judge whether a particular invocation of service provider method should be allowed within a configured time interval.
Expand All @@ -30,7 +30,7 @@ class StatItem {

private long interval;

private AtomicInteger token;
private LongAdder token;

private int rate;

Expand All @@ -39,32 +39,35 @@ class StatItem {
this.rate = rate;
this.interval = interval;
this.lastResetTime = System.currentTimeMillis();
this.token = new AtomicInteger(rate);
this.token = buildLongAdder(rate);
}

public boolean isAllowable() {
long now = System.currentTimeMillis();
if (now > lastResetTime + interval) {
token.set(rate);
token = buildLongAdder(rate);
lastResetTime = now;
}

int value = token.get();
boolean flag = false;
while (value > 0 && !flag) {
flag = token.compareAndSet(value, value - 1);
value = token.get();
while (getToken() > 0 && !flag) {
LiZhenNet marked this conversation as resolved.
Show resolved Hide resolved
token.decrement();
flag = true;
}

return flag;
}

public int getRate() {
return rate;
}

long getLastResetTime() {
return lastResetTime;
}

int getToken() {
return token.get();
long getToken() {
return token.sum();
}

@Override
Expand All @@ -76,4 +79,10 @@ public String toString() {
.toString();
}

private LongAdder buildLongAdder(int rate) {
LongAdder adder = new LongAdder();
adder.add(rate);
return adder;
}

}