Thursday, June 25, 2020

[Multi threading Interview Question ]Rate Limiter Implementation in java

There was one interesting problem I have encounter while preparing for a multithreading coding interview.

Question: We have an application for which we need to implement RateLimiter, 
Rate Limiter is an interface which will play a role to limit the number of Request client send to Server in a given time.

In the Current Question, it was asked to implement a rate limit who will do 2 things.

1) It will only allow one client to send 100 requests in 1 hrs. ( one client will be identified by the client Id).
2) It will allow a total of 10000 requests to be passed to the server in 1 hrs.

Rate Limiter Interface 
interface RateLimiter{

boolean accept(String clientId);

Java Implementation of Rate Limiter 

When we need to Implement such things where there is any restriction of accessing the resource for limited count We always start thinking using Semaphores  
Why Semaphores? 
Because it maintains the multi-access locking on its own with defined number of threads to access the critical section.

class MyRateLimiter  {
    private Semaphore semaphore;
    private int maxPermits;
    private TimeUnit timePeriod;
    private ScheduledExecutorService scheduler;
    public static MyRateLimiter create(int permits, TimeUnit timePeriod) {
    MyRateLimiter limiter = new MyRateLimiter(permits, timePeriod);
        return limiter;
    private MyRateLimiter(int permits, TimeUnit timePeriod) {
        this.semaphore = new Semaphore(permits);
        this.maxPermits = permits;
        this.timePeriod = timePeriod;
    public boolean tryAcquire() {
        return semaphore.tryAcquire();
    public void stop() {
    public void schedulePermit() {
        scheduler = Executors.newScheduledThreadPool(1);
        scheduler.scheduleAtFixedRate(() -> {
            semaphore.release(maxPermits - semaphore.availablePermits());
        }, 0, 1, timePeriod);


	class RateLimiterImpl implements RateLimiter{

private static long MINUTE_TIME_LIMIT=1000*60L; // update as per question
private static long REQUEST_ALLOWED_PER_MINUTE=10000; // Update as per question
Queue<Long> q = new LinkedList<>();
private static int minuteLimit=100;

private Map<String, Optional<MyRateLimiter>> limiters = new ConcurrentHashMap<>();
public boolean accept(String clientId) {
if(!hit(System.currentTimeMillis())) {
return false;
Optional<MyRateLimiter> rateLimiter = getRateLimiter(clientId);
if(rateLimiter.isPresent()) {
boolean canAcquire= rateLimiter.get().tryAcquire();
return q.add(System.currentTimeMillis());
return false;
private boolean hit(long timestamp) {
while(!q.isEmpty() && timestamp-q.peek() >= MINUTE_TIME_LIMIT) q.poll();
return true;
return false;
private Optional<MyRateLimiter> getRateLimiter(String clientId) {
        return limiters.computeIfAbsent(clientId, id -> {
            return Optional.of(createRateLimiter(id));
private MyRateLimiter createRateLimiter(String clientId) {
        return MyRateLimiter.create(minuteLimit, TimeUnit.MINUTES);


Main Class Calling

public class RateLimiterDemo {

public static void main(String[] args) {

RateLimiter limiter = new RateLimiterImpl();
        System.out.println("test1 " + limiter.accept("test1"));
        System.out.println("test1 " +limiter.accept("test1"));
        System.out.println("test1 " +limiter.accept("test1"));
        System.out.println("test1 " +limiter.accept("test1"));
        System.out.println("test2 " +limiter.accept("test2"));
        System.out.println("test2 " +limiter.accept("test2"));
        System.out.println("test2 " +limiter.accept("test2"));
        System.out.println("test2 " +limiter.accept("test2"));
        System.out.println("test1 " +limiter.accept("test1"));



You can also check the Code from HERE 

Hope this will help you in understanding the Code

Tuesday, June 16, 2020

101 Most Useful Websites on Internet

The Most Useful Websites and Web Apps

  1.— take a snapshot of any web page and it will exist forever even if the original page is gone.
  2. — create freehand doodles and watch them magically transform into beautiful drawings powered by maching learning.
  3.  — check the current speed of your Internet connection.
  4.  — create pixel-perfect slide decks and broadcast your presentations to an audience of any size from anywhere.
  5. — take high-resolution screenshots of web pages on mobile and desktops.
  6.  – accurate and quick voice recognition in your browser itself.
  7. — upload an image and find similar pictures on the web.
  8. – copy special characters and emojis that aren’t on your keyboard.
  9.  – the best place to learn coding online.
  10.  — ambient noises to help you improve focus and boost productivity.
  11.  – millions of icons for all kinds of projects. Also try 39 and 36.
  12.  – scan any suspicious file or email attachment for viruses.
  13.  – gets answers directly without searching – see more wolfram tips.
  14.  – track flight status at airports worldwide.
  15.  – the best place to download images absolutely free.
  16.  — an online library of free HD videos you can use everywhere. Also see 76.
  17.  – a less confusing view of the world time zones.
  18.  – a simple online timer for your daily needs.
  19.  – pick random numbers, flip coins, and more.
  20.  — replace your email with a mailbox that pays when you reply to someone’s email.
  21.  – upload an image of any text and quickly determine the font family.
  22.  – the best collection of open source fonts that you can use anywhere without restrictions.
  23.  — draw and build your own fonts and use them in any application.
  24.  — transform your handwriting into a real font.
  25. – find data hidden in your photographs – see more EXIF tools.
  26.  — broadcast yourself live over the Internet without any complicated setup.
  27.  — access other computers or allow others to remote access your computer over the Internet.
  28.  – design from scratch or re-model your home in 3D.
  29.  – lets you quickly edit PDF in the browser without Acrobat.
  30.  – create diagrams, wireframe and flowcharts in the browser.
  31.  — make voice and video calls in your browser with Skype.
  32.  – recognize text from scanned PDFs – see other OCR tools.
  33.  – for sharing really big files online.
  34. — peer to peer file transfer over WebRTC without any middleman.
  35.  — like Apple AirDrop but for the web. Share files directly between devices in the same network without having to upload them to any server first.
  36.  – the site lets you download free Kindle books.
  37.  — check your writing for spelling, style, andgrammatical errors.
  38.  – print music sheets, write your own music online ( review).
  39.  – translate web pages, PDFs and Office documents.
  40.  – create paintings and sketches with a wide variety of brushes.
  41.  – discover new sites that are similar to what you like already.
  42.  – create mind-maps, brainstorm ideas in the browser.
  43.  – get color ideas, also extract colors from photographs.
  44.  — make beautiful graphics, presentations, resumes and more with readymade template designs.
  45.  – when your friends are too lazy to use Google on their own.
  46.  – when you need to find the name of a song.
  47.  — see all your past Google searches, also among most important Google RLs
  48.  – send an online fax for free – see more fax services.
  49.  – setup your own private chat room in micro-seconds.
  50.  – create text notes that will self-destruct after being read.
  51.  – quickly search domain names for your next big idea!
  52.  – find if your favorite website is offline or not?
  53.  – the perfect tool for measuring your site performance online.
  54.  — find the web hosting company, email provider and everything else about a website.
  55.  – find definitions of slangs and informal words.
  56.  – consult this site before choosing a seat for your next flight.
  57.  – Track flight status at airports worldwide.
  58.  – create custom Google Maps with scribbles, pins and custom shapes.
  59.  – find if that email offer you received is real or just another scam.
  60.  – master touch-typing with these practice sessions.
  61.  — a beautiful todo app and task manager. Also see Trello.
  62.  – quickly capture effective notes during meetings.
  63.  — Turn Google Slides in animated GIF presentations.
  64.  – create a connection between all your online accounts.
  65.  — search for your desired username across hundreds of social networks and omain names.
  66.  — create anonymous and secret text notes and much more.
  67. — create flipbook animations, includes an onion skin tool to let you see the revious frame as you draw the next one.
  68.  — create engaging whiteboard videos and presentations with your own voiceovers. lso see
  69. — Record your own voice or upload an audio file without creating any account. Also see
  70.  — build one-page fully responsive websites that look good on every screen.
  71.  — make stunning video presentations with voice narration and wow everyone.
  72. — the easiest way to record a podcast that you can distribute on iTunes without have to pay for hosting.
  73.  — learn to speak Chinese, French, Spanish or any other language of your choice.
  74.  — an offline playground for building web projects in HTML, CSS and javascript.
  75.  — create your own comic strips with your own characters and move them into any one.
  76.  — a full-featured vector drawing tool that works everywhere.
  77.  – an excellent layer-based online image editor.
  78.  — create vector graphics and export them as SVG or PNG files.
  79. twitterbots — create your own Twitter bots that can auto-reply, DM, follow people and more.
  80.  — learn the art of meditation and reduct stress, focus more and even sleep better.
  81.  — a directory of free online courses offered by universities worldwide.
  82.  — discover museums, famous paintings and art treasure from all around the world.
  83.  — step-by-step guides on how to build anything and everything.
  84.  — make data-driven graphics, charts and infographics. Also see 18 and
  85.  — create interactive wireframes and product mockups.
  86. — make marketing videos and branded stories for Instagram, Facebook and YouTube trailers. Also, see 13 and 11.
  87.  — Take bite-sized courses on a variety of topics, chapters are delivered by email every morning.
  88. – send rich-text emails with gmail mail merge.
  89.  — whether you need a vacuum cleaner or an SD card, this is the best product recommendation website on the Internet.
  90.  — Create Amazon price watches and get email alerts when the prices drop.
  91.  — download mock data to fill the rows in your Excel spreadsheet.
  92.  — a WYSIWYG editor to draw ASCII diagrams that you can embed in emails and tweets.
  93.  — the easily way to post and schedule updates on Twitter, Instagram, LinkedIn, Google+ and Facebook.
  94.  — create disposable email addresses for putting inside sign-up forms.
  95. whereami — find the postal address of your current location on Google maps.
  96.  — create and share interactive reports, newsletters, presentations, and for storytelling.
  97.  — the perfect web scraping tool that lets you extract data from nearly any website.
  98.  — build your own apps for Android and iOS by dragging blocks instead of writing code. Also see: 36
  99.  — a huge collection of free movies curated from YouTube.
  100.  — find freelancers and subject experts to work on any kind of project.
  101.  – a clean alternative to google search that doesn’t track you on the Internet.

Know any useful website that is missing in the list? Please let me know via comment

Hope you hind these websites useful, 

Thanks for reading