Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concurrent, randomizing/shuffling Queue?

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."

like image 645
Abdull Avatar asked Nov 04 '22 04:11

Abdull


1 Answers

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
    }
}
like image 152
Evgeniy Dorofeev Avatar answered Nov 09 '22 07:11

Evgeniy Dorofeev