gpt4 book ai didi

java - 当只有1个写入者和N个读取者时,这种情况是否不需要锁定?

转载 作者:行者123 更新时间:2023-12-01 20:14:26 25 4
gpt4 key购买 nike

HashMap 不是线程安全的。

在我的例子中:1 个编写器线程用于更新 HashMapN 个读取器线程用于从 HashMap 读取。

我发现只有 1 个不好的案例:

  1. 读者 N 读取了值 V1
  2. 作者将 V1 更新到 V2
  3. 读者N使用值V1(但现在是V2)

如果在我的行业,我们可以容忍这种情况,还有其他不好的情况吗?

最佳答案

如果读取器迭代 HashMap 并且同时写入器修改它,可能会出现更严重的问题。通常,对此类集合的修改(在 C# 或 Python 等其他语言中)会使其所有迭代器失效。

来自documentation :

Note that this implementation is not synchronized. If multiple threads access a hash map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more mappings; merely changing the value associated with a key that an instance already contains is not a structural modification.)

关于java - 当只有1个写入者和N个读取者时,这种情况是否不需要锁定?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18043364/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com