Created
October 12, 2018 02:14
-
-
Save VarunVats9/ab2b422a833fcc06a006751dfd4f1671 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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(); | |
| } | |
| } | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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