blog rss feed

Introduction to reducing thread contention in Java

Keywords:

Last editor: Dave Cherry, last modified: Oct 25, 2009

Using a copy on write list instead of synchronization

Copy on write lists provide a very quick win in terms of removing synchronization. I believe that a significant use case is providing a thread safe list for java's Listener (AKA observer) pattern. Copy on write lists make the assumption that the list does not update frequently, and is mainly used for reading. If this is not the case, the overhead may be worse than synchronizing.

java.util.concurrent.CopyOnWriteArrayList implements the List interface and infact is also a random access container (implements RandomAccess). Once you've established that copy on write is the correct way to go, you need to do no more than change to using this new class. Thats it, really simple.

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

public class Concurrent
{
private List<ActionListener> listeners;
public Concurrent()
{
listeners = new CopyOnWriteArrayList<ActionListener>();
}

public void addActionListener(ActionListener listener)
{
// note, no synchronized.
listeners.add(listener);
}

public void removeActionListener(ActionListener listener)
{
// note, no synchronized.
listeners.remove(listener);
}

public void fireActionEvent()
{
// now we fire the listener event, note again there is no need
// to synchronize first.
for (ActionListener listener : listeners)
{
listener.actionPerformed(
new ActionEvent(this, 1, "HELLO"));
}
}
}

Copy on write provides thread safe access by copying the list every time it is changed, this means that when you call get or take an iterator, it is the snapshot at the time you took it. If there is a subsequent change while iterating the iterator will not see it.

<< 1 2 3 4 >>

Please leave a comment



Search

Blog calendar

blog: previous month September 2010 blog: next month
su mo tu we th fr sa
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30