Java/Maven

CopyOnWriteArrayList in Java

I am reading Java Concurrency in Practise. Priceless if you know a thing or two about concurrency already, but would like to brush up on the theory and also learn one or two new developments. The book is extremely well-written.

And here is a little something I would like to share. In the book Brian Goetz glides over this, but this is so amazing, that it deserves a deeper look.

// CopyOnWriteTest.java

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

public class CopyOnWriteTest {

	private static void f( List l ) {
		l.add( 2 );
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		List copyOnWriteList = new CopyOnWriteArrayList();
		List simpleList = new ArrayList();
		copyOnWriteList.add( 1 );
		simpleList.add( 1 );
		Iterator copyOnWriteIterator1 = copyOnWriteList.iterator();
		Iterator simpleListIterator1 = simpleList.iterator();
		f( copyOnWriteList );
		Iterator copyOnWriteIterator2 = copyOnWriteList.iterator();
		Iterator simpleListIterator2 = simpleList.iterator();
		// debug point on the output line just below
		System.out.println(copyOnWriteList);
	}

}

And when we debug into it we see this amazing picture (comments in red on the right):

CopyOnWriteArrayList debug screen

CopyOnWriteArrayList debug screen

As you see the normal non-thread safe ArrayList iterator holds reference to the collection itself. Whereas the clever little CopyOnWrite iterator creates a clone of the underlying array every time a modification is made, so whenever an iterator is called it just gets the latest clone – which doesn’t change throughout the life of the iterator. Rather new clones are created.

Now there is another way of doing this – where we don’t abstract away the reference and therefore when the collection is modified in a function we don’t see that in the caller. But this is not true here and if you let the little example run, you will see it print [1, 2], which is brilliant! 2 is added in the function f.

I should point out that Vector, which is thread safe, looks exactly like the ArrayList here.

For those searching for uniqueness guarantees there is CopyOnWriteArraySet, which uses CopyOnWriteArrayList underneath, so all of the same features hold.

Links

Standard

One thought on “CopyOnWriteArrayList in Java

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s