Java concurrency: Understanding CopyOnWriteArrayList and CopyOnWriteArraySet

Java has a huge amount of useful collections and several are made specifically for use in concurrent code like the ConcurrentHashMap.

Two sometimes very useful classes are the CopyOnWriteArrayList and CopyOnWriteArraySet. They implement the java.util.List and the java.util.Set interface respectively.

Let’s focus on the CopyOnWriteArrayList to understand what it is all about. Contrary to the ArrayList, this class is thread safe. This means when you use it from several threads no undefined state can occur in the list.
As will all data structures it is important to understand when to use them. As the name CopyOnWrite says, a copy of the whole list is made each time you write to the list like adding an element or remove an element. As you can figure out yourself, this can be pretty expensive when your list is large.
This means that a CopyOnWriteArrayList (and CopyOnWriteArraySet) is mostly useful when you have few modifications but many reads because reads are very cheap and don’t require synchronization.

When you iterate over a CopyOnWriteArrayList and CopyOnWriteArraySet the iterator uses a snapshot of the underlying list (or set) and does not reflect any changes to the list or set after the snapshot was created. The iterator will never throw a ConcurrentModificationException.

Here is a code example:

Note: This is not production ready code, no proper exception handling, etc

Here is the output of this code:

As you can see the for loop only prints the numbers 1-5 and the number 10 is not printed in the for loop as it was not present when the snapshot of the iterator was taken.

CopyOnWriteArrayList and CopyOnWriteArraySet (which is implemented with a CopyOnWriteArrayList) are special data structures for use cases where you want to share the data structure among several threads and have few writes and many reads.
Always make sure to do a performance test for your code on real hardware to see how it performs in your application. And make sure to read the javadoc for all the methods to really understand how the data structures work.
Of course you can also use CopyOnWriteArrayList and CopyOnWriteArraySet from other JVM languages like Scala, Clojure, JRuby or Groovy.

Immutable collections.
Sometimes you just need to create the list or set once and then later only read from it. In this case I recommend having a look at the immutable collections from Guava.. They are always thread safe (as is every really immutable object) and are a better alternative to the wrapped immutable collections that come with the JDK. See the Guava website for why that is the case.

One of his clients was a formerly homeless man who argued that the city should spend the money on housing programs and other initiatives to benefit struggling low income residents, instead of on a new stadium that Kroenke, who is privately financing the Rams’ new home in Inglewood, California, could afford to build himself.As part of the settlement, the NFL admitted no fault. A league official speaking to Congress recently acknowledged for the first time a definite link between football and chronic traumatic encephalopathy, the degenerative brain disease found in dozens of former players after their deaths. But the appeals court said that admission was not grounds to overturn the settlement.While spending thirty five interminable autumn days in the scorching cheap nfl jerseys Persian Gulf, we acquired a lifeboat full of pumpkins, a fruit alien to the Middle East. Our supply officer pulled off this coup, and I thought it would be micromanaging to ask for an explanation. After we overdosed on pumpkin pie, we distributed scores of unused pumpkins for a jack o’ lantern carving contest.The ‘Rooney Rule’The ‘Rooney Rule’ was established in 2003 and named after Dan Rooney, the owner of the Pittsburgh Steelers and the chairman of the NFL’s diversity committee. It requires NFL teams to interview at least one black or ethnic minority cheap China Jerseys candidate for head coaching and senior football operation opportunities that become available, as part of a transparent and open recruitment processNEW YORK (AP) ” Football helped loft NBC to a ratings win last week, according to the Nielsen company.Its Thursday night clash between the Pittsburgh Steelers and the Indianapolis Colts was the week’s most watched show, scoring nearly 21 million viewers. The runner up was NBC’s Sunday sportscast of the Kansas City Chiefs vs. All I can say is uh uh. No way. My kids brains are the most precious things they have. They got great big astonishingly amazing brains and there is no way I going to let them risk them. Fortunately, we are not a sporty family, so I don think it will ever be an issue. But I agree that either Cheap Jerseys the sportsmanship of the game needs to change or the equipment.Another useful natural treatment for hypertension is vitamin C. Studies show that individuals with the highest Wholesale Jerseys levels of vitamin C in the blood streams generally have the lowest blood pressures. Also, vitamin Fake ray bans C supplementation (500 1000mg per day) has been shown to reduce blood pressure in a significant number of individuals. One other natural remedy for hypertension is garlic (Allium sativum). At a dose of 600 900 mg per day, garlic has been shown to bring about very significant reductions in blood pressure in individuals suffering from hypertension.

1 Comment

  1. infoj says: Reply

    Very good explanation of CopyOnWriteArrayList. One thing to add is the underlying array is declared volatile in CopyOnWriteArrayList class.
    See post about CopyOnWriteArrayList here also –

Leave a Reply

This blog is kept spam free by WP-SpamFree.