com.rabbitmq.client.impl.SetQueue Maven / Gradle / Ivy
package com.rabbitmq.client.impl;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Set;
/** A generic queue-like implementation (supporting operations addIfNotPresent
,
* poll
, contains
, and isEmpty
)
* which restricts a queue element to appear at most once.
* If the element is already present {@link #addIfNotPresent} returns false
.
*
* Elements must not be null
.
* Concurrent Semantics
* This implementation is not thread-safe.
* @param type of elements in the queue
*/
public class SetQueue {
private final Set members = new HashSet();
private final Queue queue = new LinkedList();
/** Add an element to the back of the queue and return true
, or else return false
.
* @param item to add
* @return true
if the element was added, false
if it is already present.
*/
public boolean addIfNotPresent(T item) {
if (this.members.contains(item)) {
return false;
}
this.members.add(item);
this.queue.offer(item);
return true;
}
/** Remove the head of the queue and return it.
* @return head element of the queue, or null
if the queue is empty.
*/
public T poll() {
T item = this.queue.poll();
if (item != null) {
this.members.remove(item);
}
return item;
}
/** @param item to look for in queue
* @return true
if and only if item is in the queue.*/
public boolean contains(T item) {
return this.members.contains(item);
}
/** @return true
if and only if the queue is empty.*/
public boolean isEmpty() {
return this.members.isEmpty();
}
/** Remove item from queue, if present.
* @param item to remove
* @return true
if and only if item was initially present and was removed.
*/
public boolean remove(T item) {
this.queue.remove(item); // there can only be one such item in the queue
return this.members.remove(item);
}
/** Remove all items from the queue. */
public void clear() {
this.queue.clear();
this.members.clear();
}
}