我有以下类(class)
public class LRUCache {
private HashMap<String,String> dataMap;
private HashMap<String,String> analyticsMap;
public put(String key, String value) {
dataMap.put(key, value);
String date = getCurrentDateAsString();
analyticsMap.put(key, date);
}
public get(String key) {
String date = analyticsMap.get(key);
boolean dateExpired = isDateExpired(date);
boolean value = null;
if (!dateExpired)
value = dataMap.get();
return value;
}
}
在上面的类中,我有 2 个 HashMap ,可以在 get 和 put 方法中访问它们。如何使此类线程安全?
我是否需要同步 get 和 put 来解决我的问题? 一般来说,如果我在类中有超过 1 个状态,那么我应该将它们放入同步方法中,而不是分别使用 2 个并发 HashMap 吗?
最佳答案
仅使用 ConcurrentHashMap
结构并不能使您的 LRUCache
类线程安全。您需要正确控制访问,以便在执行多步 put/get 操作时其他线程无法修改底层内容。这可以通过同步
方法或使用ReentrantReadWriteLock
读/写锁来完成。
https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/locks/ReentrantReadWriteLock.html
摘自官方Javadoc(我的亮点)https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentHashMap.html :
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.
关于java - 如何使具有多个状态的类成为线程安全的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52981967/