Java: How to remove elements from a list while iterating over/adding to it
algorithm, collections, java, list
Solution
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.
Problem
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?