Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Random;
- import java.util.concurrent.Executors;
- import java.util.concurrent.ScheduledExecutorService;
- import java.util.concurrent.ScheduledFuture;
- import java.util.concurrent.TimeUnit;
- class RateLimitedCalculator {
- private final int callLimit;
- private int callCount = 0;
- private long lastResetTime = System.currentTimeMillis();
- public RateLimitedCalculator(int callLimit) {
- this.callLimit = callLimit;
- }
- public synchronized int getSum(int a, int b) {
- long currentTime = System.currentTimeMillis();
- //to check minute by minute limit for function call
- if(currentTime - lastResetTime >= TimeUnit.MINUTES.toMillis(1) ){
- callCount = 0;
- lastResetTime = currentTime;
- }
- if ( callCount < callLimit) {
- callCount++;
- return a + b;
- } else {
- throw new RateLimitExceededException("Rate limit exceeded. Please wait before making another call.");
- }
- }
- }
- public class Main {
- public static void main(String[] args) throws InterruptedException {
- Random rand = new Random();
- int callLimit = rand.nextInt(30 - 20 + 1) + 20;
- int functionCallPerMinute = rand.nextInt(40 - 20 + 1) + 20;
- RateLimitedCalculator rateLimitedCalculator = new RateLimitedCalculator(callLimit);
- //it opens a single thread that sleeps for 2 minutes and determines how much delay and how often the function inside will be called
- ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
- ScheduledFuture<?> future = executor.scheduleAtFixedRate(() -> {
- try {
- int num1 = rand.nextInt(100000 - 1 + 1) + 1;
- int num2 = rand.nextInt(10000 - 1 + 1) + 1;
- int ans = rateLimitedCalculator.getSum(num1, num2);
- System.out.println(ans);
- } catch (RateLimitExceededException e) {
- System.err.println(e.getMessage());
- }
- }, 0, TimeUnit.SECONDS.toMillis(60 / functionCallPerMinute), TimeUnit.MILLISECONDS);
- Thread.sleep(TimeUnit.MINUTES.toMillis(2));
- future.cancel(true);
- executor.shutdown();
- }
- }
- class RateLimitExceededException extends RuntimeException {
- public RateLimitExceededException(String message) {
- super(message);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement