Parallel queue randomization / shuffling?

I'm looking for an implementation java.util.Queue

that can be accessed at the same time and where the elements are added

and / or removed

randomly. That is, I'm looking for an implementation that doesn't follow the FIFO constraint, but will make sure to shuffle the new record among the currently contained records.

Please note that according to the contractjava.util.Queue

, "queues are usually, but not necessarily, order items in FIFO (first in first).

+3


source to share


1 answer


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
    }
}

      

+1


source







All Articles