我有一个静态的HashMap和三个线程试图同时从相应的类访问HashMap。
每个线程任务都获取指定键的列表值,处理列表上的一些操作(修改列表)。并将处理后的列表放入HashMap中。
我想让其他线程尝试访问HashMap,直到当前线程完成处理和修改HashMap。
在某些情况下,水流是这样的,
HashMap检索线程A,而线程A在HashMap列表上进行处理,其他线程B检索HashMap并开始处理。
实际行为必须类似于:Thread A -> retrieves HashMap -> process -> put value in HashMap. Thread B -> retrieves HashMap -> process -> put value in HashMap. Thread C -> retrieves HashMap -> process -> put value in HashMap.
逻辑:
帮助我将逻辑转换为代码,否则任何建议都会被欣然接受。
发布于 2017-07-18 09:04:52
您可以真正地利用ReentrantReadWriteLock。下面是这方面的链接。
我会以这样的方式来实现这个特性。
public class Test {
private Map<Object, Object> map = new HashMap<>();
private ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();
public void process() {
methodThatModifiesMap();
methodThatJustReadsmap();
}
private void methodThatModifiesMap() {
//if the code involves modifying the structure of the map like 'put(), remove()' i will acquire the write reentrantReadWriteLock
reentrantReadWriteLock.writeLock().lock();
try {
//DO your thing and put() or remove from map
}
finally {
//Dont forget to unlock
reentrantReadWriteLock.writeLock().unlock();
}
}
private void methodThatJustReadsmap() {
// if all you are doing is reading ie 'get()'
reentrantReadWriteLock.readLock().lock(); // this does not block other reads from other threads as long as there is no writes during this thread's read
try {
} finally {
reentrantReadWriteLock.readLock().unlock();
}
}
}不仅您的映射是线程安全的,吞吐量也更好。
发布于 2017-03-30 14:00:58
您可以使用ConcurrentHashMap而不是HashMap。ConcurrentHashMap提供了更好的性能,并减少了在其他线程访问整个HashMap时锁定它的开销。您也可以在此页找到更多详细信息- http://crunchify.com/hashmap-vs-concurrenthashmap-vs-synchronizedmap-how-a-hashmap-can-be-synchronized-in-java/。
发布于 2017-03-30 15:27:17
您可以按照上面的建议使用ConcurrentHashMap,也可以使用类级别的locks.What,我的意思是在静态method.eg上使用同步关键字。
public class SynchronizedExample extends Thread {
static HashMap map = new HashMap();
public synchronized static void execute() {
//Modify and read HashMap
}
public void run() {
execute();
}
}另外,正如其他人所提到的,如果使用同步方法,将导致性能瓶颈,这取决于您如何创建原子函数。此外,您还可以检查类级别的锁和对象级别的锁(尽管它几乎相同,但是要检查)。
https://stackoverflow.com/questions/43120084
复制相似问题