0

I am reading from multiple files concurrently, and all of those files are adding elements to the same list.

Up till now I used a regular ArrayList, but as I understood I am actually suppose to be using CopyOnWriteArrayList in order to make my code thread safe.

Problem is, the thread safe list is copying the list on each add, and since I performing a lot of single elements adds I may run in some performance issues.

Since I am only adding to the list, and I only use it's contents after the entire files were read, hence all of the elements were added - is it possible to still use a regular ArrayList, or I may encounter some unexpected behaviour?

SockworkOrange
  • 355
  • 4
  • 14
  • 1
    Answer: Use `Collections#synchronizedList`. You _might_ get away with adding concurrently to a vanilla `ArrayList`, but you also might not get away with it. Read the duplicate link for a discussion of your problem. – Tim Biegeleisen Dec 27 '18 at 13:52
  • Or synchronize on the shared list wherever adding to the list so that only a single thread can add to the list at a time. – Andrew S Dec 27 '18 at 13:57

0 Answers0