java - Concurrent Modification Exception in LinkedList -


i'm looking way, build limited linked list. if linked list "full", first element removed , new 1 added. have "newest" "limit-size" elements.

this implemented in following way:

    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() >= maxsize) {         removefirst();     }     return success; } 

now have following problem: need calculate average of linked-list. moment, randomly concurrent modification exception or index-out-of-bounds exception. method average:

public synchronized static double movingaverage(         linkedlist<averageobject> valuelist) {     if (valuelist.isempty()) {         return 0;     }     double sum = 0;      int m = 0;     (int = 0; < valuelist.size(); i++) {         averageobject object= valuelist.get(i);         sum += object.value;         m++;     }      sum = (m != 0) ? sum / m : sum;     return sum;  } 

do know way avoid concurrent modification exceptions?

my idea is, calculate average, everytime list changed, don't have iterate through it, when want have average.

the concurrent modification problem nothing modifications add. occur regular linkedlist ... if added element while computing average. worth nothing code showed cannot generate concurrentmodificationexception @ all. (but give out-of-bounds exceptions ...)

the reason having problems here add , movingaverage methods not synchronizing correctly:

  • a synchronized instance method locks target object; i.e. list instance.
  • a static synchronized method locks class object method's declaring class; i.e. class declares movingaverage method.

if 2 threads don't lock same object, won't synchronize, , won't mutual exclusion. means add , movingaverage simultaneously reading , updating same list ... resulting in exception (or worse).

one way avoid these problems might change movingaverage method this:

public static double movingaverage(     linkedlist<averageobject> valuelist) {     synchronized (valuelist) {        ...     } } 

or this:

public synchronized doubkle movingaverage() {     ... } 

however, piece-meal. better approach might synchronize @ higher level, or use "concurrent" data structure avoids need explicit synchronizing.


Comments

Popular posts from this blog

php - mySql Join with 4 tables -

css - Text drops down with smaller window -

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -