gpt4 book ai didi

Java:单线程修改对象,多线程读取

转载 作者:行者123 更新时间:2023-11-29 19:08:23 30 4
gpt4 key购买 nike

当对象(例如 HashMap 或 ArrayList 或某些 POJO)总是由单个(相同)线程修改但可以由多个线程访问时,实现线程安全的通用方法是什么?

我最感兴趣的是 HashMap,但我需要一种通用的方法。

是否足以使其不稳定?

谢谢。

最佳答案

也许您应该看看 ConcurrentHashMap。

public class ConcurrentHashMap

extends AbstractMap

implements ConcurrentMap, Serializable

A hash table supporting full concurrency of retrievals and high expected concurrency for updates. This class obeys the same functional specification as Hashtable, and includes versions of methods corresponding to each method of Hashtable. However, even though all operations are thread-safe, retrieval operations do not entail locking, and there is not any support for locking the entire table in a way that prevents all access. This class is fully interoperable with Hashtable in programs that rely on its thread safety but not on its synchronization details.

Retrieval operations (including get) generally do not block, so may overlap with update operations (including put and remove). Retrievals reflect the results of the most recently completed update operations holding upon their onset. (More formally, an update operation for a given key bears a happens-before relation with any (non-null) retrieval for that key reporting the updated value.) For aggregate operations such as putAll and clear, concurrent retrievals may reflect insertion or removal of only some entries. Similarly, Iterators, Spliterators and Enumerations return elements reflecting the state of the hash table at some point at or since the creation of the iterator/enumeration. They do not throw ConcurrentModificationException. However, iterators are designed to be used by only one thread at a time. Bear in mind that the results of aggregate status methods including size, isEmpty, and containsValue are typically useful only when a map is not undergoing concurrent updates in other threads. Otherwise the results of these methods reflect transient states that may be adequate for monitoring or estimation purposes, but not for program control.

更多信息在这里: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentHashMap.html

它在编程上的行为与经典 HashMap 完全一样。

关于Java:单线程修改对象,多线程读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46310990/

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