java.util.concurrent

This package is a new addition since 5.0, it contains utility classes useful in concurrent programming.

A few important ones are:

  1. CopyOnWriteArrayList
  2. ConcurrentHashMap
  3. CountDownLatch
  4. CyclicBarrier
  5. Semaphore
  6. LinkedBlockingQueue
  7. Executors

CopyOnWriteArrayList

Is a threadsafe version of ArrayList, in which all mutative operations like add, set, remove etc are done by making a fresh copy of the ArrayList.

What does that CopyOnWrite really mean? And how is this construct threadsafe?

The key here is the special iterator method for this construct which when called provides a snapshot of the state of the list when the iterator was constructed. No synchronization is needed while traversing the iterator – and this way the ConcurrentModificationException is preempted.

Mutative operations on iterators themselves remove, add, set are NOT supported by these iterators and these methods will throw UnsupportedOperationException when called. This special type of  iterator will also NOT reflect any additions, removals, or changes to the list since the iterator was created.

What about Memory Consistency?

Actions in a thread prior to placing an object into a CopyOnWriteArrayList happen-before, the actions that take place after another thread accesses or removes that same object from this CopyOnWriteArrayList. So if one thread modifies an object from the list and puts it back in the CopyOnWriteArrayList, this modification and putting back operation is complete before something else happens on the same object in a different thread. Thus keeping the memory consistent between multiple threads.

What’s the cost of using a CopyOnWriteArrayList?

It is indeed very costly since the copies or snapshots need to be made for iterator. But using a CopyOnWriteArrayList is more efficient when traversal operations are much more frequenter than mutation or element-changing operations. This is also useful when you cannot or don’t want to synchronize traversals, yet need to make sure that concurrent threads do not interfere on mutations.

Situation – what happens if two different threads try to populate a CopyOnWriteArrayList at the same time starting from an empty one? For example:

Thread 1 puts A in its snapshot of the list. Thread 2 puts B in its snapshot of the same list. When they are both done, will there be A and B in the list?