[concurrency-interest] CopyOnWriteArrayList and snapshots

David M. Lloyd david.lloyd at redhat.com
Wed Mar 25 15:52:20 EDT 2009


Hm, you're right!  Cool.  It does clone the lock as well though, which 
might not be good (it uses some scary-looking Unsafe stuff, not to mention 
that the lock is not needed anyway).  I'll have to run some tests I guess.

Either way, it would be nice if that method covariantly returned COWAL<E> 
rather than Object.

- DML

On 03/25/2009 02:19 PM, Jason Mehrens wrote:
> I think CopyOnWriteArrayList.clone() will provide the snapshot behavior 
> you want.  Clone doesn't copy the backing array and only creates one 
> list object.
>  
> Jason
>  
>>
>>  + /**
>>  + * Returns a snapshot view of this list. The returned list provides
>>  + * a snapshot of the state of the list when the method was called. No
>>  + * synchronization is needed while calling the list methods. The list
>>  + * is read-only; any methods which modify the state of the list will
>>  + * throw <tt>UnsupportedOperationException</tt>.
>>  + *
>>  + * @return a snapshot of this list
>>  + */
>>  + public List<E> snapshot() {
>>  + final Object[] snapshot = getArray();
>>  + return new AbstractList<E>() {
>>  + public E get(final int index) {
>>  + return CopyOnWriteArrayList.this.get(snapshot, index);
>>  + }
>>  +
>>  + public int size() {
>>  + return snapshot.length;
>>  + }
>>  +
>>  + public Iterator<E> iterator() {
>>  + return new COWIterator<E>(snapshot, 0);
>>  + }
>>  +
>>  + public ListIterator<E> listIterator() {
>>  + return new COWIterator<E>(snapshot, 0);
>>  + }
>>  +
>>  + public ListIterator<E> listIterator(final int index) {
>>  + Object[] elements = snapshot;
>>  + int len = elements.length;
>>  + if (index<0 || index>len)
>>  + throw new IndexOutOfBoundsException("Index: "+index);
>>  + return new COWIterator<E>(elements, index);
>>  + }
>>  + };
>>  + }
>>  +
>>  private static class COWIterator<E> implements ListIterator<E> {
>>  /** Snapshot of the array **/
>>  private final Object[] snapshot;
>>  _______________________________________________
>>  Concurrency-interest mailing list
>>  Concurrency-interest at cs.oswego.edu
>>  http://cs.oswego.edu/mailman/listinfo/concurrency-interest
> 
> 
> ------------------------------------------------------------------------
> Get quick access to your favorite MSN content with Internet Explorer 8. 
> Download FREE now! 
> <http://ie8.msn.com/microsoft/internet-explorer-8/en-us/ie8.aspx?ocid=B037MSN55C0701A>


More information about the Concurrency-interest mailing list