简体   繁体   中英

Java: modifying object in a single thread, reading in multiple threads

What is a generic approach to achieve thread safety when an object (eg a HashMap or an ArrayList or some POJO) is always modified by a single (same) thread but can be accessed by multiple threads?

HashMap is of most interest for me but I need a generic approach.

Is it enough to make it volatile?

Thanks.

Maybe you should take a look at 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.

More info here : https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentHashMap.html

It behaves programmaticaly exactly like a classical hashmap.

A generic approach will not be easy to implement and will need a lot of effort on your part, and still things will go wrong (as it is too difficult). So, your best bet is ConcurrentHashMap as suggested by Gomoku7.

Generic approach will require an implementation based on locks. You will have to lock objects before update and release lock afterwords. There are different types of locks in Java. So, chose locks which suits your need. There are some tip:

  1. Final is your friend, do not mutate objects unless it is necessary, make objects final where possible
  2. Avoid creating temporary variables
  3. Use Executors and Fork/Join where possible

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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