前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >How to design and implement a blocking queue?

How to design and implement a blocking queue?

作者头像
包子面试培训
发布2018-04-19 10:47:45
5900
发布2018-04-19 10:47:45
举报
文章被收录于专栏:包子铺里聊IT包子铺里聊IT

Question:

Blocking queue related question often gets asked from Google, LinkedIn. For example, iImplement a fixed size blocking queue with the following defined functions. By blocking queue it Blocking queue related question often gets asked from Google, LinkedIn. means if the queue is empty, the dequeue thread should be blocked until some other thread enqueue anything. If the queue is full then the enqueue thread gets blocked until the dequeue thread dequeue anything from the queue.

Here is the API defined.

public interface FixedSizeBlockingQueue<E> {

// only initialize this queue once and throws Exception if the user is trying to initialize it multiple t times.

public void init(int capacity) throws Exception;

// throws Exception if the queue is not initialized

public void push(E obj) throws Exception;

// throws Exception if the queue is not initialized

public E pop() throws Exception;

// implement an atomic putList function which can put a list of object atomically. By atomically it mean the objs in the list should be next to each other in the queue. The size of the list could be larger than the queue capacity.

// throws Exception if the queue is not initialized

public void pushList(List<E> objs) throws Exception;

}

Analysis:

Here we are using some basic OS and JVM primitives to implement a blocking queue. Basically it is using monitor and lock. Java exposes those two OS primitives to programmers as Condition and ReentrantLock. Here is the explanation from Java Doc

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2014-07-21,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 包子铺里聊IT 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Question:
  • Analysis:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档