[concurrency-interest] CopyOnWriteArrayList and snapshots

Jason Mehrens jason_mehrens at hotmail.com
Wed Mar 25 15:19:48 EDT 2009


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. 
http://ie8.msn.com/microsoft/internet-explorer-8/en-us/ie8.aspx?ocid=B037MSN55C0701A
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://cs.oswego.edu/pipermail/concurrency-interest/attachments/20090325/0798b57e/attachment-0001.html>


More information about the Concurrency-interest mailing list