-2

I have two thread and a ArrayList in my program. I want to access list from my threads.

public void run() {
...
arraylist.add(myObj);
...
}

public void run() {
...
arraylist.remove(myObj);
...
}

I tried Synchronization each of thread.

 synchronized (arraylist) 
 {  
    //add or remove
 } 

but it said "Synchronization of non-final field".

mozkarakoc
  • 269
  • 6
  • 14
  • 3
    ....so make it final? anyway i think syn on ono-file is a warning, not an error – radai Mar 18 '13 at 13:39
  • see here http://stackoverflow.com/questions/6910807/synchronization-of-non-final-field – PSR Mar 18 '13 at 13:40
  • `ConcurrentModificationException` generally means you are modifying the collection **while you are iterating over it**. Generally nothing to do with threading. – OldCurmudgeon Mar 18 '13 at 13:43

2 Answers2

1

Synchronization of non-final field is only a warning that you can safely ignore. If the arraylist is only assigned in the constructor, you can declare it as final and get rid of the warning.

You need to synchronize on the list, because the remove method is not inherently thread-safe (one thread may modify the list while remove is searching for the element to be removed).

Community
  • 1
  • 1
Javier
  • 12,100
  • 5
  • 46
  • 57
0

Seems like there are other operation on arraylist without synchronization.

Synchronization of non-final field this warning gives by compiler when there are number of threads to synchronize a block of code correctly they need to synchronize on the same object instance.

Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103