Choosing the best concurrency list in Java
Any Java collection can be made to be Thread-safe like so:
List newList = Collections.synchronizedList(oldList);
Or to create a brand new thread-safe list:
List newList = Collections.synchronizedList(new ArrayList());
http://download.oracle.com/javase/6/docs/api/java/util/Collections.html#synchronizedList(java.util.List)
ConcurrentLinkedQueue
uses a lock-free queue (based off the newer CAS instruction).
had better be
List
The only List
implementation in java.util.concurrent
is CopyOnWriteArrayList. There's also the option of a synchronized list as Travis Webb mentions.
That said, are you sure you need it to be a List
? There are a lot more options for concurrent Queue
s and Map
s (and you can make Set
s from Map
s), and those structures tend to make the most sense for many of the types of things you want to do with a shared data structure.
For queues, you have a huge number of options and which is most appropriate depends on how you need to use it:
- ConcurrentLinkedQueue
- ArrayBlockingQueue
- LinkedBlockingDeque
- LinkedBlockingQueue
- PriorityBlockingQueue
- SynchronousQueue
- DelayQueue
If the size of the list if fixed, then you can use an AtomicReferenceArray. This would allow you to perform indexed updates to a slot. You could write a List view if needed.