Advertisement
Jaydeep999997

Token Bucket Filter - S1

Oct 21st, 2024
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.68 KB | Source Code | 0 0
  1. import java.util.HashSet;
  2. import java.util.Set;
  3.  
  4. class Demonstrator {
  5.   public static void main(String[] args) throws Exception {
  6.     TokenBucketFiller tokenBucketFiller = new TokenBucketFiller(5);
  7.     Set<Thread> threads = new HashSet<Thread>();
  8.  
  9.     Thread.sleep(10000);
  10.  
  11.     for (int i = 0; i < 20; i++) {
  12.       Thread thread =
  13.           new Thread(
  14.               new Runnable() {
  15.                 @Override
  16.                 public void run() {
  17.                   try {
  18.                     tokenBucketFiller.consumeToken();
  19.                   } catch (InterruptedException ie) {
  20.  
  21.                   }
  22.                 }
  23.               });
  24.       thread.setName("Thread " + i);
  25.       threads.add(thread);
  26.     }
  27.  
  28.     for (Thread thread : threads) {
  29.       thread.start();
  30.     }
  31.  
  32.     for (Thread thread : threads) {
  33.       thread.join();
  34.     }
  35.   }
  36. }
  37.  
  38. class TokenBucketFiller {
  39.   private int maxCapacity;
  40.   private int consumableTokens = 0;
  41.   private long lastConsumedTime = System.currentTimeMillis();
  42.  
  43.   public TokenBucketFiller(int maxCapacity) {
  44.     this.maxCapacity = maxCapacity;
  45.   }
  46.  
  47.   public synchronized void consumeToken() throws InterruptedException {
  48.     consumableTokens += (System.currentTimeMillis() - lastConsumedTime) / 1000;
  49.     if (consumableTokens > maxCapacity) {
  50.       consumableTokens = maxCapacity;
  51.     }
  52.  
  53.     if (consumableTokens == 0) {
  54.       Thread.sleep(1000);
  55.     } else {
  56.       consumableTokens--;
  57.     }
  58.  
  59.     lastConsumedTime = System.currentTimeMillis();
  60.  
  61.     System.out.println(
  62.         "Granting "
  63.             + Thread.currentThread().getName()
  64.             + " a token at time "
  65.             + System.currentTimeMillis());
  66.   }
  67. }
  68.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement