java - Concurrent ArrayList -
i need arraylist-like construction allowing next operations
get(int index)
add(e element)
set(int index, e element)
iterator()
because of iterator beingness used in many places, using collections#synchronizedlist
error-prone. list can grow few one thousand elements , gets used lot, i'm pretty sure, copyonwritearraylist
slow. i'll start avoid premature optimizations, i'd bet won't work well.
most accesses single-threaded reads. i'm asking what's proper info construction this.
i though wrapping synchronizedlist
in providing synchronized iterator do, won't because of concurrentmodificationexception
. concenrning concurrent behavior, need changes visible subsequent reads , iterators.
the iterator doesn't have show consistent snapshot, may or may not see updates via set(int index, e element)
operation gets used replace item updated version (containing added information, irrelevant user of iterator). items immutable.
i stated why copyonwritearraylist
not do. concurrentlinkedqueue
out of question lacks indexed access. need couple of operations rather fledged arraylist
. unless any java concurrent list-related question duplicate of this question, 1 not.
in case can utilize readwritelock access backed list, allows multiple threads read list. if 1 thread needs write access reader-thread must wait operation complete. javadoc make's clear:
a readwritelock maintains pair of associated locks, 1 read-only operations , 1 writing. read lock may held simultaneously multiple reader threads, long there no writers. write lock exclusive.
here sample:
public class concurrentarraylist<t> { /** utilize lock write operations add/remove */ private final lock readlock; /** utilize lock read operations get/iterator/contains.. */ private final lock writelock; /** underlying list*/ private final list<t> list = new arraylist(); { reentrantreadwritelock rwlock = new reentrantreadwritelock(); readlock = rwlock.readlock(); writelock = rwlock.writelock(); } public void add(t e){ writelock.lock(); try{ list.add(e); }finally{ writelock.unlock(); } } public void get(int index){ readlock.lock(); try{ list.get(index); }finally{ readlock.unlock(); } } public iterator<t> iterator(){ readlock.lock(); seek { homecoming new arraylist<t>( list ).iterator(); //^ iterate on snapshot of our list } finally{ readlock.unlock(); } }
java arraylist concurrency
No comments:
Post a Comment