Reputation: 267
i have an arraylist and i want to add and remove many items at he same(almost) time. So i decide to create 2 methods. In the first method i implement the method which contains the remove part i use something like:
//my list
ArrayList<Human> list= new ArrayList<Human>(100);
//Human is the object of the class Human
List<Human> syncList = Collections.synchronizedList(new ArrayList<Human>());
synchronized (syncList){
for (Iterator<Human> iter = list.iterator(); iter.hasNext();) {
Human = iter.next();
-
-
//using the removes method of the iterator
it.removes(something);
And in the second method (which i need to add many items) something like this:
for( ListIterator<Human> it = list.listIterator();it.hasNext();){
List<Human> syncList = Collections.synchronizedList(newArrayList<Human>());
synchronized (syncList){
-
-
//using the add method of the iterator list
it.add(something)
Now i realize that when those two void methods finished and the list called by another function don't have the appropriate behaviour. I mean that some of the elements didn't add or removed from the list. How can i fix this?any ideas?
Upvotes: 0
Views: 89
Reputation: 53694
you are synchronizing on 2 entirely different objects, hence the inconsistent behavior. your call to synchronizedList()
is returning a wrapper around the original list, on which you are synchronizing. since the 2 methods are using different wrappers, no actual synchronization is happening. you just need to synchronize on the original list implementation. of course, any other usage of the list member should also be synchronized.
Upvotes: 3