[concurrency-interest] Thread-safety of hasMoreElements() of Vector

Praveen Kumar Jha javapk at gmail.com
Thu Jul 19 11:12:38 EDT 2012


Please help me in understanding the thread-safety of hasMoreElements() of
Vector from visibility point of view. The hasMoreElements()
accesses the 'elementCount' field without synchronizing over 'Vector.this',
like it is done in nextElement() method.

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 (E)elementData[count++];
        throw new NoSuchElementException("Vector Enumeration");

This might cause a thread to see stale value of 'elementCount' and thus
hasMoreElements() might incorrectly return true or false.
Javadoc of neither Enumeration nor elements() of Vector says anything about

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://cs.oswego.edu/pipermail/concurrency-interest/attachments/20120719/d894e7e4/attachment.html>

More information about the Concurrency-interest mailing list