在Java中的并发数据结构

14 浏览
0 Comments

在Java中的并发数据结构

如何创建一个可以通过索引访问元素的并发List实例?JDK中有没有可以使用的类或工厂方法?

0
0 Comments

Concurrent data structures in Java are designed to handle multiple threads accessing and modifying the data simultaneously. One such implementation is the concurrent list, which is available in the java.util.concurrent package. In particular, the CopyOnWriteArrayList is a concurrent list implementation.

However, it should be noted that the CopyOnWriteArrayList has a drawback - it copies the entire list on every insert operation. This can lead to inefficiency, especially when there are frequent updates to the list. It is more suitable for situations where there are more read operations than write operations.

There have been cases where the CopyOnWriteArrayList does not work well. For example, in a Stack Overflow question (https://stackoverflow.com/questions/1527519), the user encountered exceptions even though they were only using the addAll method and reading the list using streams.

It is important to note that the accepted answer in that Stack Overflow question, which suggests using CopyOnWriteArrayList as a solution for concurrency with an ArrayList, is misleading. As mentioned in the comments, CopyOnWriteArrayList is not a good choice if the majority of operations involve writes rather than reads. Another answer provided by an user named "user207421" is considered more complete and informative.

To summarize, the need for concurrent data structures arises from the requirement to handle concurrent access and modification of data by multiple threads. The CopyOnWriteArrayList is a concurrent list implementation in Java, but it may not be efficient when there are frequent updates to the list. It is more suitable for scenarios where there are more read operations than write operations.

0