Advertisement
ridwan100

java challange

May 2nd, 2024 (edited)
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.39 KB | None | 0 0
  1. import java.util.Random;
  2. import java.util.concurrent.Executors;
  3. import java.util.concurrent.ScheduledExecutorService;
  4. import java.util.concurrent.ScheduledFuture;
  5. import java.util.concurrent.TimeUnit;
  6.  
  7. class RateLimitedCalculator {
  8. private final int callLimit;
  9. private int callCount = 0;
  10. private long lastResetTime = System.currentTimeMillis();
  11.  
  12. public RateLimitedCalculator(int callLimit) {
  13. this.callLimit = callLimit;
  14. }
  15.  
  16. public synchronized int getSum(int a, int b) {
  17. long currentTime = System.currentTimeMillis();
  18. //to check minute by minute limit for function call
  19. if(currentTime - lastResetTime >= TimeUnit.MINUTES.toMillis(1) ){
  20. callCount = 0;
  21. lastResetTime = currentTime;
  22. }
  23. if ( callCount < callLimit) {
  24. callCount++;
  25.  
  26. return a + b;
  27. } else {
  28. throw new RateLimitExceededException("Rate limit exceeded. Please wait before making another call.");
  29. }
  30. }
  31. }
  32.  
  33. public class Main {
  34. public static void main(String[] args) throws InterruptedException {
  35. Random rand = new Random();
  36. int callLimit = rand.nextInt(30 - 20 + 1) + 20;
  37. int functionCallPerMinute = rand.nextInt(40 - 20 + 1) + 20;
  38. RateLimitedCalculator rateLimitedCalculator = new RateLimitedCalculator(callLimit);
  39. //it opens a single thread that sleeps for 2 minutes and determines how much delay and how often the function inside will be called
  40. ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
  41. ScheduledFuture<?> future = executor.scheduleAtFixedRate(() -> {
  42. try {
  43. int num1 = rand.nextInt(100000 - 1 + 1) + 1;
  44. int num2 = rand.nextInt(10000 - 1 + 1) + 1;
  45. int ans = rateLimitedCalculator.getSum(num1, num2);
  46. System.out.println(ans);
  47. } catch (RateLimitExceededException e) {
  48. System.err.println(e.getMessage());
  49. }
  50. }, 0, TimeUnit.SECONDS.toMillis(60 / functionCallPerMinute), TimeUnit.MILLISECONDS);
  51.  
  52. Thread.sleep(TimeUnit.MINUTES.toMillis(2));
  53.  
  54. future.cancel(true);
  55. executor.shutdown();
  56. }
  57. }
  58.  
  59. class RateLimitExceededException extends RuntimeException {
  60. public RateLimitExceededException(String message) {
  61. super(message);
  62. }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement