0

I have multiple threads constantly iterating through an ArrayList called "clients".

When they disconnect I want to remove a single client from the list but I am aware that it could cause a concurrent modification exception.

Should I surround all usage of the ArrayList with the Synchronized block or is that not a good idea?

Also can the ArrayList be read by multiple threads without a problem?

Thanks,

(The client list is constantly iterated by the UDP thread that sends data to all the clients)

  • CopyOnwrite arraylist is a good solution but in your case which you need to remove items, you have to keep in mind that, removing elements from iterator is not possible and you have to choose other solutions like this: http://stackoverflow.com/questions/5612470/remove-elements-from-copyonwritearraylist – Mr.Q Dec 18 '16 at 10:26

1 Answers1

2

I might not have a full information, but it seems that you always read and only sometimes write (change) to the array list. In this case, probably you should consider using:

Copy On Write Array List implementation

It should be better than using a regular synchronization because you don't want to get synchronized on read operations.

Here is an article that explains more pro- and -contra of using CopyOnWriteArrayList solution.

halfer
  • 19,824
  • 17
  • 99
  • 186
Mark Bramnik
  • 39,963
  • 4
  • 57
  • 97