MCPcopy Create free account
hub / github.com/diyhi/bbs / UniqueBlockingQueue

Class UniqueBlockingQueue

src/main/java/cms/utils/UniqueBlockingQueue.java:23–181  ·  view source on GitHub ↗

基于 LinkedBlockingQueue 实现的只包含唯一元素的阻塞队列。 我们将插入的元素序列化到队列中,否则队列中可能会出现重复的元素。 @param 元素类型

Source from the content-addressed store, hash-verified

21 * @param <T> 元素类型
22 */
23public class UniqueBlockingQueue<T> extends AbstractQueue<T> implements BlockingQueue<T> {
24 private ConcurrentHashSet<T> mElementSet = new ConcurrentHashSet<T>();//唯一标记
25 private BlockingQueue<T> mBlockingQueue;
26
27 /**
28 * UniqueBlockingQueue 的构造函数
29 *
30 * @param capacity 阻塞队列的容量
31 */
32 public UniqueBlockingQueue(int capacity) {
33 mBlockingQueue = new LinkedBlockingQueue<>(capacity);
34 }
35
36 @Override
37 public synchronized void put(T e) throws InterruptedException {
38 if (!mElementSet.contains(e)) {
39 mBlockingQueue.put(e);
40 mElementSet.add(e);
41 }
42 }
43
44 @Override
45 public synchronized boolean offer(T e) {
46 //接口描述表明,offer 只能因容量原因而失败,但我们是因唯一性原因而失败。
47 if (mElementSet.contains(e)) {
48 return false;
49 }
50
51
52 if (mBlockingQueue.offer(e)) {
53 mElementSet.add(e);
54 return true;
55 }
56 return false;
57 }
58
59 @Override
60 public synchronized boolean offer(T e, long timeout, TimeUnit unit) throws InterruptedException {
61
62 // 接口描述表明,offer 只能因容量原因而失败,但我们是因唯一性原因而失败。
63 // 由于唯一性原因而失败。
64 if (mElementSet.contains(e)) {
65 return false;
66 }
67 if (mBlockingQueue.offer(e, timeout, unit)) {
68 mElementSet.add(e);
69 return true;
70 }
71 return false;
72 }
73
74 @Override
75 public T take() throws InterruptedException {
76
77 T e = mBlockingQueue.take();
78 mElementSet.remove(e);
79 return e;
80 }

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…