Java Reference
In-Depth Information
stopUpdatingThread();
}
How It Works
Java comes with many concurrent collection options. Which collection to use depends
on how the read operations compare with the write operations within the context of
your application. If writing occurs far and in-between compared with reads, using a
copyOnWriteArrayList
instance is most efficient because it doesn't
block
(stop)
other threads from reading the list and is thread-safe to iterate over (no
Concur-
rentModificationException
is thrown when iterating through it). If there are
the same number of writes and reads, using a
SynchronizedList
is the preferred
choice.
In solution 1, the
CopyOnWriteArrayList
is being updated while you traverse
the list. Because the recipe uses the
CopyOnWriteArrayList
instance, there is no
need to worry of thread safety when iterating through the collection (as is being done in
this recipe by using the
stream
). It is good to note that the
CopyOnWriteAr-
rayList
offers a snapshot in time when iterating through it. If another thread modi-
fies the list as you're iterating through it, changes are that the modified list will not be
visible when iterating.
Note
Locking properly depends on the type of collection being used. Any collec-
tions returned as a result of using
Collections.synchronized
can be locked via
the collection itself (
synchronized (collectionInstance)
). However, some
more efficient (newer) concurrent collections such as the
ConcurrentMap
cannot be
used in this fashion because their internal implementations don't lock in the object it-
self.
Solution 2 creates a synchronized list, which is created by using the
Collec-
tions
helper class. The
Collection.synchronizedList()
method wraps a
List
object (it can be
ArrayList
,
LinkedList
, or another
List
implementer)
into a list that synchronizes the access to the list operations. Each time that you need to
iterate over a list (either by using the
stream
, a
for
loop, or an iterator) you must be
aware of the concurrency implications for that list's iterator. The
CopyOnWriteAr-
rayList
is safe to iterate over (as specified in the Javadoc), but the
synchron-
izedList
iterator must be synchronized manually (also specified in the
Collec-