package zab.atomics.bag;

import java.util.concurrent.atomic.AtomicLong;

/**
 * An atomic, lock-free and wait-free storage of items.  It can store up to 32 items.
 * 
 * The bag keeps references to the stored items after they are removed.  Use it
 * only for objects you do not expect to be garbage-collected.
 *  
 * @author zlatinb
 *
 * @param <T> type of the items stored
 */
public class AtomicBag<T> {
    
    private static final int FREE = 0;
    private static final int CLAIM = 1;
    private static final int FULL = 2;
    
    private final Object[] storage = new Object[32];
    
    private final AtomicLong state = new AtomicLong();
    
    private static long freeMask(int i) {
        long mask = 1 << (i << 1);
        mask |= (mask << 1);
        return ~mask;
    }
    
    private static long free(long state, int i) {
        return state & freeMask(i);
    }
    
    private static long claim(long state, int i) {
        long freed = free(state,i);
        return freed | (CLAIM << (i <<1));
    }
    
    private static long full(long state, int i) {
        long freed = free(state,i);
        return freed | (FULL << (i <<1));
    }
    
    private static int get(long state, final int i) {
        state &= (~freeMask(i));
        return (int)(state >>> (i << 1));
    }
    
    /**
     * @param item to store
     * @return true if stored, false if there was no space.
     */
    public boolean store(T item) {
        while(true) {
            final long s = state.get();
        }
    }
    
    public static void main(String[] ar) {
        AtomicBag<?> as = new AtomicBag<Object>();
        System.out.printf("%x\n",as.get(12,1));
    }

}

@@ -1439,24 +1439,70 @@
 e(T item) %7B%0A
+        // find a free slot%0A        int slot;%0A
         whil
@@ -1547,24 +1547,690 @@
 tate.get();%0A
+            slot = -1;%0A            for (int i = 0; i %3C 32; i++) %7B%0A                if (get(s,i) != FREE)%0A                    continue;%0A                slot = i;%0A                break;%0A            %7D%0A            if (slot %3C 0)%0A                return false;%0A            %0A            // try to claim it%0A            long claimState = claim(s,slot);%0A            if (state.compareAndSet(s,claimState))%0A                break;%0A        %7D%0A        %0A        // write%0A        storage%5Bslot%5D = item;%0A        while(true) %7B%0A            final long s = state.get();%0A            long fullState = full(s,slot);%0A            if (state.compareAndSet(s,fullState))%0A                return true;%0A
         %7D%0A  

store method