This question is a more special case of the problem described (and solved) in this question.
I have two methods, stopAndRemove(ServerObject server) and a close() method. The later should close all servers and remove them from the server list. The list is defined as
List<ServerObject> server.
I do not want to have almost the same code from stopAndRemove in closeCurrentlyOpen, so I want to do something like:
public void closeCurrentlyOpen() {
for(ServerObject server : this.servers) {
stopAndRemove(server)
}
}
This won't work, as this will cause a ConcurrentModificationException. I tried to make a copy of the list
List<ServerObject> copyList = new ArrayList<ServerObject>(this.servers);
and use that as the list for the foreach-loop. But then it might be possible that an other thread appends a Server to the servers list while I am iterating over copyList but closeCurrentlyOpen is supposed to result in an emtpy list. As the addServerToList method is synchronized to the servers-list, doing this
public void closeCurrentlyOpen() {
synchronized(this.servers) {
for(ServerObject server : this.servers) {
stopAndRemove(server)
}
}
}
will solve the problem with modifications. But then I can not synchronize the code in the stopAndRemove method which is necessary if it is directly called.
I seems to me that the design of this three methods probably needs a workover. Ideas anybody?
Even though java. util. ArrayList provides the remove() methods, like remove (int index) and remove (Object element), you cannot use them to remove items while iterating over ArrayList in Java because they will throw ConcurrentModificationException if called during iteration.
If you want to delete elements from a list while iterating, use a while-loop so you can alter the current index and end index after each deletion.
An element can be removed from a Collection using the Iterator method remove(). This method removes the current element in the Collection. If the remove() method is not preceded by the next() method, then the exception IllegalStateException is thrown.
The Best Answer is At the end the whole list will have the letter "D" as its content. It's not a good idea to use an enhanced for loop in this case, you're not using the iteration variable for anything, and besides you can't modify the list's contents using the iteration variable.
Split off a method stop() from stopAndRemove(). Then write the loop with an explicit iterator, do the stop and then iterator.remove().
"and" in a method name is a code smell.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With