Tuesday, 5 July 2022

Bucket4j: refill the tokens in greedy manner

Refill#greedy method Creates the Refill that does refill of tokens in greedy manner, it will try to add the tokens to bucket as soon as possible.

 

For example refill "10 tokens per 1 second" will add 1 token per each 100 millisecond, in other words refill will not wait 1 second to regenerate whole bunch of 10 tokens.

 

Signature

public static Refill greedy(long tokens, Duration period)

Argument 'tokens' specifies amount of tokens and 'period' specifies the period within tokens will be fully regenerated.

 

Note

The three refills bellow do refill of tokens with same speed:

a.   Refill.greedy(600, Duration.ofMinutes(1));

b.   Refill.greedy(10, Duration.ofSeconds(1));

c.    Refill.greedy(1, Duration.ofMillis(100));

 

Find the below working application.

 

HelloWorld.java

package com.sample.app;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

import io.github.bucket4j.Bandwidth;
import io.github.bucket4j.Bucket;
import io.github.bucket4j.Refill;

public class HelloWorld {

	private static Bucket bucket;

	private static void getResource() {

		if (bucket.tryConsume(1)) {
			System.out.println("Resource accessed....");
			return;
		}

		System.err.println("Too Many Requests, all the tokens consumed");
	}

	public static void main(String[] args) throws InterruptedException {
		Bandwidth limit = Bandwidth.classic(5, Refill.greedy(10, Duration.ofSeconds(30)));
		bucket = Bucket.builder().addLimit(limit).build();

		while (true) {
			TimeUnit.SECONDS.sleep(1);
			getResource();
		}
	}

}

 

Sample output


 

  

Previous                                                 Next                                                 Home

No comments:

Post a Comment