Besides managing threads, Concurrency API includes interfaces and classes that help to coordinate access to collections across multiple tasks.
Using concurrent collections is extremely convenient in practice. Concurrent collections often include performance enhancements that avoid unnecessary synchronization. So developer may concentrate more on working with the functionality provided by collections than trying to coordinate access to them.
The purpose of concurrent collection classes is to solve common memory consistency errors. A memory consistency error occurs when two threads have inconsistent views of what should be the same data. Conceptually, writes on one thread must be available to another thread if it accesses the concurrent collection after the write has occured.
When two threads try to modify the same non-concurrent collection (add or remove elements), the JVM may throw a ConcurrentModificationException at runtime. Concurrent collections are ordering read/write access such that all access is consistent, thus avoiding memory consistence errors.
Concurrent collection classes should be used anytime developer is going to have multiple threads modify a collection object outside a synchronized block or method, even if no concurrency problem is expected. On the other hand, if all of the threads are accessing an established immutable or read-only collection, a concurrent collection class is not required.
Common concurrent classes are listed in the table below :
|Class Name||Java Collections Framework Interface||Elements Ordered ?||Sorted ?||Blocking ?|
Using concurrent collections strongly resembles working with non thread-safe collections, since they implement mostly the same interfaces and have the same methods implementations.
Let’s look at different types of concurrent collections more thoroughly :