Vector (using an array realization, thread synchronization)

Vector and ArrayList collections, like internal use arrays to achieve, but it is the thread synchronization, the code synchronization:

public Enumeration<E> elements() {
        return new Enumeration<E>() {
            int count = 0;
            public boolean hasMoreElements() {
                return count < elementCount;
            }
            public E nextElement() {
                synchronized (Vector.this) {
                    if (count < elementCount) {
                        return elementData(count++);
                    }
                }
                throw new NoSuchElementException("Vector Enumeration");
            }
        };
    }

 

The same time, only one thread can edit Vector, avoiding multiple threads at the same time will not write what I said in the ArrayList collection array bounds phenomenon, but synchronization takes more time, so the speed is slow additions and deletions by source Vector can be found in the capacity is not enough when it doubled the capacity of the default extension, expansion source as follows:

private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + ((capacityIncrement > 0) ? capacityIncrement : oldCapacity);
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        elementData = Arrays.copyOf(elementData, newCapacity);
    }

 

Guess you like

Origin www.cnblogs.com/Mr-RanX/p/11261356.html