Whenever we use java.util Collection classes, we have that if one thread changes a collection while another thread is traversing through it using an iterator, then any call to iterator.hasNext() or iterator.next() will throw ConcurrentModificationException. Even the synchronized collection wrapper classes SynchronizedMap and SynchronizedList are only conditionally thread-safe, which means all individual operations are thread-safe but compound operations where flow of control depends on the results of previous operations may be subject to threading issues. The question is: How to avoid this problem without affecting the performance. Note: I am aware of CopyOnWriteArrayList.
Whenever we use java.util Collection classes, we have that if one thread changes a
Share
You can use
CopyOnWriteArrayListorConcurrentHashMapetc. as you mentioned above or you can useAtomic*classes which are working with CAS.If you weren’t aware of
Atomic*classes they definitely worth a look! You may check out this question.So to answer your question you have to choose the right tools for the task. Since you do not share the context with us I can just guess. In some situations CAS will perform better in others the concurrent Collections will.
If something isn’t clear you can always check out the official Oracle Trails: Lesson: Concurrency