LinkedBlockingQueue经常用于线程间的消息队列。一个或多个消费者线程阻塞在take操作,生产者线程往队列里面offer新的消息。有时候,可能希望不要在队列中有重复的请求。我实现的AntiDuplicateLinkedBlockingQueue可实现此目的。代码很简单,就是用一个LinkedList来实现队列,一个HashSet来实现去重。
=========================代码的分隔线==============================
import java.util.AbstractMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map.Entry;
public class AntiDuplicateLinkedBlockingQueue<Key,
Value> {
private
final LinkedList<Entry<Key,
Value>> list = new
LinkedList<Entry<Key,
Value>>();
private
final HashSet<Key> keySet = new
HashSet<Key>();
public
synchronized int size() {
return list.size();
}
public
synchronized boolean offer(Key key, Value value) {
if (keySet.contains(key)) {
return false;
}
list.add(new AbstractMap.SimpleEntry<Key,
Value>(key, value));
keySet.add(key);
notifyAll();
return true;
}
public
synchronized Value take() throws InterruptedException {
while (list.size() == 0) {
wait();
}
Entry<Key, Value> entry =
list.removeFirst();
keySet.remove(entry.getKey());
return entry.getValue();
}
public
synchronized void clear() {
list.clear();
keySet.clear();
}
}