0

There are fail safe iterators in java which creates the copy of the collection to iterate over to provide fail safe behavior.

Enumeration works on legacy java classes Vector, Stack and HashTable etc(These are Synchronized collections).

How Enumeration in java is fail safe, how it provide fail safe behavior? Does it also creates the copy of the collection for iteration?

Yogi Devendra
  • 711
  • 1
  • 4
  • 18
  • What do you mean by "fail-safe"? – Eran Oct 29 '17 at 08:09
  • Like CouncurrentHashMap iterator is fail-safe, because it creates a copy of the collection object to iterate over, so that if another thread tries to alter the collection object structure (By adding or removing an element) it does not disturb the iterator. Similarly Enumeration is also a fail safe iterator but how it provides the fail-safe behavior is under question here. – Anshul Sharma Oct 29 '17 at 08:14
  • 2
    What is the source of the statement that "Enumeration is fail-safe"? It is not, so the "why it is fail-safe" question does not apply. – Oleg Estekhin Oct 29 '17 at 08:17

1 Answers1

0

I wouldn't call Enumeration fail-safe.

At least not the implementation returned by Vector's elements() 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 elementData(count++);
                }
            }
            throw new NoSuchElementException("Vector Enumeration");
        }
    };
}

This implementation can cause bad behavior without throwing an exception if you modify the Vector while iterating over it.

For example, the following code will cause an infinite loop, in which each call to els.nextElement () will return the same element "a".

Vector<String> vec = new Vector<> ();
vec.add ("a");
vec.add ("b");
vec.add ("c");
Enumeration<String> els = vec.elements ();
while (els.hasMoreElements ()) {
    System.out.println (els.nextElement ());
    vec.add (0,"d");
}
Eran
  • 387,369
  • 54
  • 702
  • 768
  • Does this mean, it does not through any exception even in case of concurrent modification. Can we say that it is neither fail-fast nor fail-safe (in terms of concurrent modification in multi threaded environment). – Anshul Sharma Oct 29 '17 at 08:56
  • @AnshulSharma That's correct, unless you call `Vector`'s `remove()` between a call to `hasMoreElements()` and a call to `nextElement()`, which may cause `nextElement()` to throw `NoSuchElementException`. – Eran Oct 29 '17 at 08:59
  • Thanks @Eran this is helpful. – Anshul Sharma Oct 29 '17 at 09:10