I am looking for a java.util.Queue
implementation that can be accessed concurrently and where elements are added
and/or removed
randomly. That is, I'm looking for an implementation that does not follow the FIFO constraint, but makes sure to shuffle a new entry among the currently contained entries.
Please notice that according to the java.util.Queue
contract, "queues typically, but do not necessarily, order elements in a FIFO (first-in-first-out) manner."
I think you can implement your own version based on java.util.concurrent.PriorityBlockingQueue, like this
class ConcurrenRandomizingQueue<E> extends AbstractQueue<E> {
static Random r = new Random();
Queue<Entry> q = new PriorityBlockingQueue<Entry>();
static class Entry implements Comparable<Entry> {
Object e;
int p;
Entry(Object e) {
this.e = e;
this.p = r.nextInt();
}
public int compareTo(Entry e) {
return Integer.compare(p, e.p);
}
}
public boolean offer(E e) {
return q.offer(new Entry(e));
}
public E poll() {
Entry e = q.poll();
if (e == null)
return null;
return (E) e.e;
}
public E peek() {
Entry e = q.peek();
if (e == null)
return null;
return (E) e.e;
}
public int size() {
return q.size();
}
public Iterator<E> iterator() {
return null; // TODO
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With