简体   繁体   English

多个线程在Java中修改集合?

[英]Multiple threads modifying a collection in Java?

The project I am working on requires a whole bunch of queries towards a database. 我正在开发的项目需要对数据库进行大量查询。 In principle there are two types of queries I am using: 原则上我使用两种类型的查询:

  1. read from excel file, check for a couple of parameters and do a query for hits in the database. 从excel文件中读取,检查几个参数并对数据库中的命中进行查询。 These hits are then registered as a series of custom classes. 然后将这些命中注册为一系列自定义类。 Any hit may (and most likely will) occur more than once so this part of the code checks and updates the occurrence in a custom list implementation that extends ArrayList. 任何命中都可能(并且很可能会)多次出现,因此这部分代码会检查并更新扩展ArrayList的自定义列表实现中的事件。

  2. for each hit found, do a detail query and parse the output, so that the classes created in (I) get detailed info. 对于找到的每个匹配,执行详细查询并解析输出,以便在(I)中创建的类获取详细信息。

I figured I would use multiple threads to optimize time-wise. 我想我会使用多个线程来优化时间。 However I can't really come up with a good way to solve the problem that occurs with the collection these items are stored in. To elaborate a little bit; 但是我无法想出一个很好的方法来解决这些项目存储在集合中的问题。详细说明一下; throughout the execution objects are supposed to be modified by both (I) and (II). 在整个执行对象中,应该由(I)和(II)修改。

I deliberately didn't c/p any code, as it would be big chunks of code to make any sense.. I hope it make some sense with the description above. 我故意没有c / p任何代码,因为这将是大块的代码有任何意义..我希望它与上面的描述有一定道理。

Thanks, 谢谢,

In Java 5 and above, you may either use CopyOnWriteArrayList or a synchronized wrapper around your list . 在Java 5及更高版本中,您可以使用CopyOnWriteArrayList列表中同步包装器 In earlier Java versions, only the latter choice is available. 在早期的Java版本中,只有后一种选择可用。 The same is true if you absolutely want to stick to the custom ArrayList implementation you mention. 如果你绝对想要坚持你提到的自定义ArrayList实现,情况也是如此。

CopyOnWriteArrayList is feasible if the container is read much more often than written (changed), which seems to be true based on your explanation. 如果容器的读取频率比写入(更改)的频率高得多,则CopyOnWriteArrayList是可行的,根据您的解释,这似乎是正确的。 Its atomic addIfAbsent() method may even help simplify your code. 它的原子addIfAbsent()方法甚至可以帮助简化代码。

[Update] On second thought, a map sounds more fitting to the use case you describe. [更新]第二个想法,地图听起来更适合您描述的用例。 So if changing from a list to eg a map is an option, you should consider ConcurrentHashMap . 因此,如果从列表更改为例如地图是一个选项,则应考虑使用ConcurrentHashMap [/Update] [/更新]

Changing the objects within the container does not affect the container itself, however you need to ensure that the objects themselves are thread-safe. 更改容器中的对象不会影响容器本身,但是您需要确保对象本身是线程安全的。

Just use the new java.util.concurrent packages. 只需使用新的java.util.concurrent包。

Classes like ConcurrentLinkedQueue and ConcurrentHashMap are already there for you to use and are all thread-safe. ConcurrentLinkedQueueConcurrentHashMap这样的类已经可供您使用,并且都是线程安全的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM