在我的应用程序中,我将使用 map 。
- 多个线程将数据写入此 map 。写操作太多。
- 但是,每次写入时,提供给 map 的数据都有不同的键。
- map 中的数据不会在应用程序的任何时候被读取。
- 偶尔,内容会被转储到一个文件中。
我想知道以下内容:
- 在这种情况下,是否需要同步写入方法?
- ConcurrentHashMap 是否适合我的需求?
- 如果不是,那么在此应用程序中使用什么是正确的 Map 实现? 案例?
最佳答案
关注这些点:
The data that is fed to the map has a different key during every write
The data in the map would not be read at any point in the application
您根本不需要 map
。我假设当您声明不会读取 map 中的数据时,您的意思是您没有执行 map.get(someKey)
而是遍历整个 map 以将数据存储在文件中(或您使用的任何数据源)。
这一点:
- Once in a while the content would be dumped to a file
强化上述建议。
关注这一点:
- Multiple threads would be writing data to this map.The write operations are too many.
最好的建议是使用 BlockingQueue
.作为实现,您可以使用 LinkedBlockingQueue
.
如果您使用 Java 同步从 Map
转储数据并希望/需要以 Map
的形式恢复此数据,则使用 ConcurrentHashMap
。如果这不是您的用例的一部分,因为您将通过其他方式从文件中读取数据,那么请避免使用 Map
并使用 BlockingQueue
。
关于java - 如果多个线程写入单个映射,则使用哪个映射实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31542356/