Reputation: 13
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.
Upvotes: 1
Views: 140
Reputation: 941455
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.
Upvotes: 0
Reputation: 547
Yes. The exceptions are most likely due to synchronization issues. You definitely need to lock it. But also you may want to control the number of threads that access the list as the system scales. Otherwise the threads may go slower waiting for this list.
Upvotes: 0
Reputation: 12611
I'd lock it. The actual price of the lock should be very low for the add remove scenarios. It sounds like the cleanup process would be the hog. It all depends on how many things it has to clean up though.
Upvotes: 2