Does the ReadWriteLock presented in the explanation offer a more modern solution to the problem?
Although this question asked about synchronization within the context of traditional threads,
a solution to the problem could be to use a more modern approach using the
concurrent package.
The ReadWriteLock from the concurrent package requires the following imports:
However, something that caught my attention was the fact that the OpenJDK 17 implementation no longer uses ReentrantLock (there is a comment from the maintainer stating that they prefer builtin monitors over ReentrantLock )
- OpenJDK 17:https://github.com/openjdk/jdk17/blob/m ... .java#L429
Anyway, regardless of the CopyOnWriteArrayList implementation, would that be a valid option to the question? (Excluding the fact that it would no longer be an ArrayList<String> but a CopyOnWriteArrayList<String>).
Yes, using CopyOnWriteArrayList is also a valid approach. As per its JavaDoc API description, "it is useful when you cannot or don't want to synchronize traversals, yet need to preclude interference among concurrent threads.", which suits very well for the given situation.
The solution in the explanation is to show the concept behind preventing multiple reads and writes from interfering/corrupting the collection. Using CopyOnWriteArrayList in the example would not show what goes behind the scene. It is a blackbox that you can just use without worrying about multithreading issues.
If you like our products and services, please help us by posting your review here.