Skip to content

Instantly share code, notes, and snippets.

@VarunVats9
Created October 12, 2018 02:14
Show Gist options
  • Select an option

  • Save VarunVats9/ab2b422a833fcc06a006751dfd4f1671 to your computer and use it in GitHub Desktop.

Select an option

Save VarunVats9/ab2b422a833fcc06a006751dfd4f1671 to your computer and use it in GitHub Desktop.
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class LeakyBucket {
public static final int API_REQUEST_LIMIT_OF_THE_SERVER = 5;
public static final BlockingQueue<Runnable> blockingLifo = new ArrayBlockingQueue<>(API_REQUEST_LIMIT_OF_THE_SERVER);
public static final RejectedExecutionHandler handler = new RejectedExecutionHandler() {
@Override
public void rejectedExecution(final Runnable r, final ThreadPoolExecutor executor) {
System.out.println("API access BLOCKED");
}
};
public static void main(String[] args) {
ThreadPoolExecutor loadBalancer = new ThreadPoolExecutor(
5, 5, 0L, TimeUnit.SECONDS, blockingLifo, handler);
while (true) {
final int randomUser = ThreadLocalRandom.current().nextInt(10);
loadBalancer.submit(new UserApiRequest(randomUser));
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class UserApiRequest implements Runnable {
private int user;
public UserApiRequest(final int randomUser) {
this.user = randomUser;
}
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
final String userId = "User-" + user;
System.out.println("API access given for : [" + userId + "]");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment