Wednesday, June 15, 2016

Buttercola: Fast ID Generator



Buttercola: Fast ID Generator
已知一个叫get_ids()的API能够耗时1s并返回100个各不相同的id(第二次call返回的和第一次的也不会有任何重复),有个待实现的函数叫get_one_id(),每秒最多被call 100次,每次call要能返回一个新的id。题目就是利用get_ids()实现get_one_id(),follow up是保证每次call get_one_id()不能等待超过1s
Use a queue to store 100 IDs. Once the queue is empty, refill the queue by calling the get_ids(). 
  Queue<Integer> queue;
   
  public Solution() {
    queue = new LinkedList<>();
  }
   
   
  public Integer get_one_id() {
    // Take 1 sec
    if (queue.isEmpty()) {
      List<Integer> ids = get_ids();
      for (Integer id : ids) {
        queue.offer(id);
      }
    }
     
    return queue.poll();
  }
   
  public List<Integer> get_ids() {
    List<Integer> result = new ArrayList<>();
    Random randomGenerator = new Random();
     
    // Generate 100 ids which takes 1 sec
    for (int i = 0; i < 100; i++) {
      result.add(randomGenerator.nextInt(1000));
    }
     
    // Sleep 1 sec
    try {
      Thread.sleep(1000);                 //1000 milliseconds is one second.
    } catch(InterruptedException ex) {
      Thread.currentThread().interrupt();
    }
     
    return result;
  }
Follow-up: What if each time we call get_one_id(), the waiting time is on longer than 1s?
In the previous solution, if the queue is empty, we have to call get_ids() to get 100 ids which takes 1s. In order to shorten the waiting time, we need to overlap those two processes. 

The idea is to use two threads. One thread calls get_one_id(), which consumes the IDs, another thread call get_ids(), which feeds the queue. The threshold is 100, i.e., when the queue has 100 IDs, the get_ids() will be triggered and feed 100 IDs into the queue. Since get_one_id() is called no more than 100 times per second, in this way calling the get_one_id() will not be blocked any more. 

In fact, this is a classic producer/consumer problem. 
  public static void main(String[] args) {
    BlockingQueue bq = new BlockingQueue();
    Producer p1 = new Producer(bq);
    Consumer c1 = new Consumer(bq);
     
    p1.start();
    c1.start();
  }
}
class BlockingQueue {
  private Queue<Integer> queue;
  private int threshold = 100;
   
  public BlockingQueue() {
    queue = new LinkedList<>();
    // feed 100 ids first
    List<Integer> ids = get_ids();
    for (Integer id : ids) {
      queue.offer(id);
    }
  }
   
  public synchronized void put() throws InterruptedException {
    while (queue.size() != threshold) {
      wait();
    }
     
    // feed 100 ids
    List<Integer> ids = get_ids();
    for (Integer id : ids) {
      queue.offer(id);
    }
     
    notifyAll();
  }
   
  public synchronized Integer take() throws InterruptedException {
    while (queue.size() == 0) {
      wait();
    }
     
    Integer result = queue.poll();
    notifyAll();
     
    return result;
  }
   
  public List<Integer> get_ids() {
    List<Integer> result = new ArrayList<>();
    Random randomGenerator = new Random();
     
    // Generate 100 ids which takes 1 sec
    for (int i = 0; i < 100; i++) {
      result.add(randomGenerator.nextInt(1000));
    }
     
    // Sleep 1 sec
    try {
      Thread.sleep(1000);                 //1000 milliseconds is one second.
    } catch(InterruptedException ex) {
      Thread.currentThread().interrupt();
    }
     
    return result;
  }
}
class Consumer extends Thread {
  private BlockingQueue bq;
  public Consumer(BlockingQueue bq) {
    this.bq = bq;
  }
   
  public void run() {
    // print 500 ids
    for (int i = 0; i < 1000; i++) {
      try {
        Integer result = bq.take();
        System.out.println(result);
      } catch (InterruptedException ex) {
        Thread.currentThread().interrupt();
      }
    }
  }
}
class Producer extends Thread {
  private BlockingQueue bq;
   
  public Producer(BlockingQueue bq) {
    this.bq = bq;
  }
   
  public void run() {
    try {
      bq.put();
    } catch (InterruptedException ex) {
      Thread.currentThread().interrupt();
    }
  }
Read full article from Buttercola: Fast ID Generator

Labels

Review (572) System Design (334) System Design - Review (198) Java (189) Coding (75) Interview-System Design (65) Interview (63) Book Notes (59) Coding - Review (59) to-do (45) Linux (43) Knowledge (39) Interview-Java (35) Knowledge - Review (32) Database (31) Design Patterns (31) Big Data (29) Product Architecture (28) MultiThread (27) Soft Skills (27) Concurrency (26) Cracking Code Interview (26) Miscs (25) Distributed (24) OOD Design (24) Google (23) Career (22) Interview - Review (21) Java - Code (21) Operating System (21) Interview Q&A (20) System Design - Practice (20) Tips (19) Algorithm (17) Company - Facebook (17) Security (17) How to Ace Interview (16) Brain Teaser (14) Linux - Shell (14) Redis (14) Testing (14) Tools (14) Code Quality (13) Search (13) Spark (13) Spring (13) Company - LinkedIn (12) How to (12) Interview-Database (12) Interview-Operating System (12) Solr (12) Architecture Principles (11) Resource (10) Amazon (9) Cache (9) Git (9) Interview - MultiThread (9) Scalability (9) Trouble Shooting (9) Web Dev (9) Architecture Model (8) Better Programmer (8) Cassandra (8) Company - Uber (8) Java67 (8) Math (8) OO Design principles (8) SOLID (8) Design (7) Interview Corner (7) JVM (7) Java Basics (7) Kafka (7) Mac (7) Machine Learning (7) NoSQL (7) C++ (6) Chrome (6) File System (6) Highscalability (6) How to Better (6) Network (6) Restful (6) CareerCup (5) Code Review (5) Hash (5) How to Interview (5) JDK Source Code (5) JavaScript (5) Leetcode (5) Must Known (5) Python (5)

Popular Posts