Java 同步块 vs concurrentHashMap vs Collections.synchronizedMap [英] Java synchronized block vs concurrentHashMap vs Collections.synchronizedMap

查看:22
本文介绍了Java 同步块 vs concurrentHashMap vs Collections.synchronizedMap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说如果有一个同步方法并且在该方法中,我会更新一个这样的哈希图:

Say If have a synchronized method and within that method, I update a hashmap like this:

public synchronized void method1()
{
    myHashMap.clear();
    //populate the hashmap, takes about 5 seconds.
}

现在当method1正在运行并且hashmap正在重新填充时,如果有其他线程尝试获取hashmap的值,我认为它们会被阻塞?

now while the method1 is running and the hashmap is being re-populated, if there are other threads tring to get the value of the hashmap, I assume they will get blocked?

现在,如果我将 hashmap 更改为 ConcurrentHashMap,而不是使用同步方法,如下所示,行为是什么?

Now instead of using sync method, if I change hashmap to ConcurrentHashMap like below, what's the behaviour?

public void method1()
{
     myConcurrentHashMap.clear();
    //populate the hashmap, takes about 5 seconds.
}

如果我使用 Collections.synchronizedMap 会怎样?是一样的吗?

what if i use Collections.synchronizedMap ? is it the same?

推荐答案

如果你想让 HashMap 的所有读写操作同步,你需要把 synchronize 在所有访问 HashMap 的方法上;仅阻止一种方法是不够的.

If you want to have all read and write actions to your HashMap synchronized, you need to put the synchronize on all methods accessing the HashMap; it is not enough to block just one method.

ConcurrentHashMap 允许线程安全地访问您的数据而无需锁定.这意味着您可以在一个线程中添加/删除值,同时在另一个线程中获取值而不会遇到异常.另请参阅ConcurrentHashMap 的文档

ConcurrentHashMap allows thread-safe access to your data without locking. That means you can add/remove values in one thread and at the same time get values out in another thread without running into an exception. See also the documentation of ConcurrentHashMap

这篇关于Java 同步块 vs concurrentHashMap vs Collections.synchronizedMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆