title: Nullpointer exception in LinkedList while using for-each loop
body: <p>I came across very odd Java behaviour, and I don't know if it is a bug, or
  am I missing something.</p>
  
  <p>The code simply goes through the stateStack (LinkedList) list and destroy all the states.</p>
  
  <pre><code>public void clearStates()
  {
      LogFactory.getLog(StateController.class.getName())
        .info( "Clearing states. #ofstates="+stateStack.size());
      for (State state : stateStack)  // Line 132 (see exception)
      {
          state.destroy();
      }
  
      // ...
  } 
  </code></pre>
  
  <p>The following exception was trowed:</p>
  
  <pre><code>INFO  controllers.StateController : Clearing states. #ofstates=1
  java.lang.NullPointerException\
      at java.util.LinkedList$ListItr.next(LinkedList.java:891)
      at *.controllers.StateController.clearStates(StateController.java:132)
      // ... //
  </code></pre>
  
  <p>This code usually works without a problem and has been in the production for more than a year.</p>
  
  <p>Is it possible that this is Java bug? </p>
  
  <p>/<strong>* Update *</strong>/</p>
  
  <p>destroy() call does not modify stateStack. If it would I guess Java would
  throw ConcurrentModificationException. </p>
  
  <p>stateStack was populated with 1 state, which overrides destroy, but only does
  local modifications. The super implementation than prints additional log ("Destroying state..."), which was not in the log file, so I guess the exception was thrown at
  the beginning of iteration.</p>
  
  <pre><code>public void destroy()
  {
      destroyed = true;
      LogFactory.getLog(State.class.getName()).info( "Destorying state : "+getClass().getName());
      propertyChangeSupport.firePropertyChange(PROP_DESTROYED, null, this);
  }
  </code></pre>