@Override
    public <T> T[] toArray(T[] arr) {

        if (arr == null) {
            return null;
        }
        T[] retMe;
        int currTailIndex;
        do {
            currTailIndex = tailIndex.get(); // start from the tailIndex (technically the first slot *after* the tail)

            ArrayList<T> returnArrayList = new ArrayList<T>();
            //Go through the SoftReference Buffer and retrieve elements that have not been GCed.
            //Restore these elements into a strong reference and add them into an arraylist
            //which will be used to retrieve an array that will be returned to the caller.
            for (int i = 0, index = currTailIndex; i < elements.size(); i++, index++) {
                index = index % elements.size();
                T element = (T) elements.get(index).get();
                if (element != null) {
                    returnArrayList.add(element);
                }
            }

            retMe = (T[]) Array.newInstance(arr.getClass().getComponentType(), returnArrayList.size());
            returnArrayList.toArray(retMe);

            // Make sure tailIndex wasn't updated by another thread during the copy
        } while (tailIndex.compareAndSet(currTailIndex, currTailIndex) == false);

        return retMe;
    }
@ Override public < T > T [ ] toArray ( T [ ] arr ) { if ( arr == null ) { return null ; } T [ ] retMe ; int currTailIndex ; do { currTailIndex = tailIndex . get ( ) ; ArrayList < T > returnArrayList = new ArrayList < T > ( ) ; for ( int i = 0 , index = currTailIndex ; i < elements . size ( ) ; i ++ , index ++ ) { index = index % elements . size ( ) ; T element = ( T ) elements . get ( index ) . get ( ) ; if ( element != null ) { returnArrayList . add ( element ) ; } } retMe = ( T [ ] ) Array . newInstance ( arr . getClass ( ) . getComponentType ( ) , returnArrayList . size ( ) ) ; returnArrayList . toArray ( retMe ) ; } while ( tailIndex . compareAndSet ( currTailIndex , currTailIndex ) == false ) ; return retMe ; }
@return an atomic copy of the queue. The elements in the returned array
are in order from head to tail so it can be iterated normally.