Concurrent Arrays in Java
So, there is a concurrent hashmap in Java, the advantage of which is not to lock down the whole hash table, but only portions of it. I was wondering whether there was such a cons开发者_JAVA技巧truction for arrays. Particularly when an array is being resized locking down the whole array is not desirable, especially in real time applications. Anything out there?
There is AtomicIntegerArray
(and the similar AtomicReferenceArray
) that may fit your description. But as noted by Marcelo - you can't resize arrays. So you only get concurrent safety without the need to explicitly lock (on) the entire array.
An array ... in which elements may be updated atomically
Java 6 also adds an interesting collection called ConcurrentSkipListSet
...average log(n) time cost for thecontains, add
, andremove
operations and their variants. Insertion, removal, and access operations safely execute concurrently by multiple threads. Iterators are weakly consistent, returning elements reflecting the state of the set at some point at or since the creation of the iterator. They do not throw ConcurrentModificationException, and may proceed concurrently with other operations...
You can always use one of these:
java.util.Collections.synchronizedList(List<T> list)
java.util.Collections.synchronizedCollection(Collection<T> collection)
java.util.Collections.synchronizedSet(Set<T> set)
Your requirements aren't clear. Perhaps the java.util.collections copy-on-write list or set will do, too.
The closest thing in the standard library is the CopyOnWriteArrayList. That's 'concurrent' in the sense that there is no lock, and so not contention, for readers; however, access for writers is serialized, and is very expensive. The tradeoff is a bit sharper than for the concurrent hashmap: reads are really cheap, but writes are really expensive.
It seems like it might be possible to write a list implementation which used the striped lock strategy of the concurrent hashmap for single-element, size-preserving operations like get
and set
(and perhaps add
to the end of the list), but the copy-on-write strategy for size-altering operations like add
and remove
. It might be rather complicated to get a sensible ordering of size-preserving and size-altering mutations, though.
精彩评论