I have a shared instance of a List that gets updated randomly by various threads (objects are only added to it via the threads). I then have a timer that executes on a set interval which removes records from the List based on a set of criteria–specifically, if the records are older than x minutes. What I am finding is that as my system scales out and the threads become more numerous, the method that cleans the list will randomly throw exceptions as it iterates it. I presume this is due to contention between the List updates and the removal of records. Is the best way to prevent the exceptions to put a lock on the shared instance as the iteration is done? If so, what are the negatives of doing so. If not, what other options are there?
I’m sure this is a pretty basic question but I’m new to threading issues.
I don’t think that was stated strong enough: you HAVE to lock it. Beware that a List is not a great collection object to do this, removing the old items costs O(n^2). Consider creating a new List from the old one or using LinkedList.