我们可以在多线程环境下不同步的情况下使用Hashmap的containsKey()
方法吗?
Note: Threads are only going to read the Hashmap. The map is initialized once, and is never modified again.
最佳答案
这实际上取决于访问 map 的方式/时间。
假设 map 被初始化一次,并且再也没有修改过,那么像 containsKey()
这样不修改内部状态的方法应该是安全的。
但在这种情况下,您应该确保您的 map 确实是不可变的,并且是安全发布的。
现在如果在您的特定情况下状态在您的程序过程中确实发生了变化,那么不,它是不安全的。 来自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.
在这种情况下,你应该使用ConcurrentHashMap
,或者外部同步。
关于java - Hashmap 的 containsKey 方法是线程安全的,如果映射被初始化一次,并且永远不会被再次修改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54925533/