Appropriate atomic pointer to use in this case

150 Views Asked by At

Let's say I have an implementation of the Herlihy-Wing Queue in Java :

public class HWQueue<T> {
    AtomicReference<T>[] items;
    AtomicInteger tail;
    static final int CAPACITY = 1024;

    public HWQueue() {
        items =(AtomicReference<T>[])Array.newInstance(AtomicReference.class, CAPACITY);
        for (int i = 0; i < items.length; i++) {
            items[i] = new AtomicReference<T>(null);
            // Each value in 'items' set to 'null' 
            // to indicate empty position for enqueue
        }
        tail = new AtomicInteger(0);
    }

    public void enq(T x) {
        int i = tail.getAndIncrement();
        items[i].set(x);
    }

    public T deq() {
        while (true) {
            int range = tail.get();
            for (int i = 0; i < range; i++) {
                T value = items[i].getAndSet(null);
                if (value != null) {
                    return value;
                }
            }
        }
    }
}

I am using the type atomic<int *> data type for the items array. But in the enqueue method, I need to do something like items[i].store(&x) which is wrong obviously since it's a dangling reference. How to do this operation correctly? If I use heap, I don't know when to free that memory either. How can I achieve this?

0

There are 0 best solutions below