Home > Back-end >  Java guava ratelimiter current-limiting surprising result
Java guava ratelimiter current-limiting surprising result

Time:02-27

The import com.google.com mon. Util. Concurrent. RateLimiter;

Public class RateLimitTest {

The static RateLimiter r=RateLimiter. Create (5.0);
Public static void main (String [] args) {
for(int i=0; i<10; I++)
{
New Thread (new Runnable () {
@ Override
Public void the run () {
System. The out. Println (Thread. CurrentThread (). The getName () + ":" + r.t ryAcquire ());
}
}). The start ();

}
}
}

Results:
Thread 1: true
Thread - 4: false
Thread - 3: false
Thread - 6: false
Thread - 5: false
Thread - 9: false
Thread - 8: false
Thread - 7: false
Thread - 10: false
Thread - 2: false

I don't know why the token bucket is set the initial size of the 5, but the thread of execution result, only one thread can get license, please help see what reason

CodePudding user response:

Probability question
Set 5, it is said allow five times per second, estimate your cycle too fast, the frequency of more than five times per second (although it is the request of 10 times, but the frequency is too fast), so that other threads may get the token

CodePudding user response:

Public void the run () {
System. The out. Println (Thread. CurrentThread (). The getName () + ":" + r.t ryAcquire ());
}


How many seconds you add a dormant inside

CodePudding user response:

reference 1st floor qybao response:
probability question
Set 5, it is said allow five times per second, estimate your cycle too fast, the frequency of more than five times per second (although it is the request of 10 times, but the frequency is too fast), so that other threads might get token


But tryAcquire () method is thread-safe, inside should not ah

CodePudding user response:

Sleep time, look at the results
  • Related