Consider the scenario below:
- The application is multi-threaded and it has one static ArrayList used globally.
- The application has one thread that reconstruct the ArrayList entirely from data read from database from time to time.
- The application has N threads reading from this global ArrayList in parallel.
What is the best approach to thread-safe the multiple parallel reads and the occasional altering of the ArrayList object?
If it contains a cache of readonly data read from a database and is never modified, you probably don’t need any synchronisation.
You do of course need to construct the list completely before setting the global reference, e.g.:
In the event of a race condition when a writer thread replaces the list, another thread can get the “old” copy of the list, but if it’s not being modified this old copy will still be consistent.