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

Joe Bowbeer joe.bowbeer at gmail.com
Thu Jul 19 12:11:15 EDT 2012


The Enumeration API is not suitable for multi-threaded use because there is
a window for change between the hasMoreElements call and the subsequent
nextElement call.

In almost all cases the Enumeration is consumed in the same thread in which
it is produced.

The strange corner case that you envision is: one thread creates an
Enumeration and hands it to another thread.  The other thread calls
hasNextElement and may see a stale value for elementCount, causing it to
end too early (not calling nextElement) or to fail unexpectedly when it
does call nextElement.

With this scenario in mind, using "synchronized" in hasMoreElements is more
correct, though in practice I doubt it will make any difference.

Joe

On Thu, Jul 19, 2012 at 8:12 AM, Praveen Kumar Jha wrote:

> Hello,
>
> 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 thread-safety.
>
> Regards,
> Praveen
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://cs.oswego.edu/pipermail/concurrency-interest/attachments/20120719/41261a04/attachment.html>


More information about the Concurrency-interest mailing list