title: Concurrent Modification Exception in LinkedList
body: <p>I'm looking for a good way, to build a limited linked list. If the linked list is "full", the first element will be removed and the new one will be added. So I always have the "newest" "limit-size" elements.</p>
  
  <p>This is implemented in the following way:</p>
  
  <pre><code>    private int maxSize;
  
  public LimitedLinkedList(int maxSize) {
      this.maxSize = maxSize;
  }
  
  @Override
  public synchronized boolean add(E object) {
      boolean success = super.add(object);
      while (this.size() &gt;= maxSize) {
          removeFirst();
      }
      return success;
  }
  </code></pre>
  
  <p>Now I have the following problem: I need to calculate the average of the linked-list. This is the moment, where I randomly get the concurrent modification exception or an index-out-of-bounds exception. My method for average:</p>
  
  <pre><code>public synchronized static double movingAverage(
          LinkedList&lt;AverageObject&gt; valueList) {
      if (valueList.isEmpty()) {
          return 0;
      }
      double sum = 0;
  
      int m = 0;
      for (int i = 0; i &lt; valueList.size(); i++) {
          AverageObject object= valueList.get(i);
          sum += object.value;
          m++;
      }
  
      sum = (m != 0) ? sum / m : sum;
      return sum;
   }
  </code></pre>
  
  <p>Do you know a good way to avoid concurrent modification exceptions? </p>
  
  <p>My only idea is, to calculate the average, everytime the list is changed, so I don't have to iterate through it, when I want to have the average.</p>