修改ConcurrentHashMap中的值 [英] Modifying values in ConcurrentHashMap

查看:218
本文介绍了修改ConcurrentHashMap中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ConcurrentHashMap中有分段的概念。这意味着如果两个线程试图访问ConcurrentHashMap,它会分为两个块,默认大小为16。

In ConcurrentHashMap there is concept of segmentation. What it means if two threads are trying to access ConcurrentHashMap they it gets divided in two blocks and default size of blocks is 16.

现在假设在ConcurrentHashMap只有一个场景中两个元素和两个不同的线程来了,thread1尝试修改第一个值,thread2尝试修改第二个值。在这种情况下,ConcurrentHashMap是否会进行分段?

Now suppose in a scenario where ConcurrentHashMap has only two elements and two different threads comes and thread1 tries to modify first value and thread2 tries to modify second value. In this case whether ConcurrentHashMap will go for segmentation?

现在在不同的场景中,两个线程都尝试修改ConcurrentHashMap如何处理这种情况的相同值?通过使用锁定机制或还有其他什么?

Now in a different scenario both the threads try to modify same value how ConcurrentHashMap will handle this situation? By using locking mechanism or is there something else ?

推荐答案

ConcurrentHashMap有几个存储桶。密钥根据其哈希值映射到其中一个桶中。当您添加或检索值时,与该键关联的存储桶将被锁定。

ConcurrentHashMap has several buckets. Keys are mapped, based on their hash value, into one of the buckets. When you add or retrieve a value, the bucket associated with that key is locked.

如果是您的第一个问题,则有两种可能:两个键都存在相同的水桶,或者他们住在不同的水桶里。在第一种情况下,一次只能有一个线程可以工作 - 获取锁定的第一个线程将抓住并工作,第二个线程将轮流等待。在第二种情况下,密钥位于不同的桶中,它们每个都会获得独立的锁并同时完成它们的工作。

In the case of your first question, there are two possibilities: either both keys live in the same bucket, or they live in different buckets. In the first case, only one thread can work at a time -- the first one to acquire the lock will grab it and work, the second thread will wait its turn. In the second case, where the keys are in different buckets, they'll each acquire independent locks and do their work concurrently.

对于你的第二个问题,它是<被锁定的em> bucket ,没有别的。如果两个线程尝试为同一个键存储两个值,则ConcurrentHashMap承诺这两个值中的一个将与该键相关联。 ie 如果线程A运行 map.put(Answers,2); 并且线程B运行 map.put( 答案,10); ,然后ConcurrentHashMap将确保地图有效并包含 2 10 for Answers,但它不会对这两者中的哪一个做出任何承诺。

For your second question, it is the bucket that gets locked, and nothing else. If two threads try to store two values for the same key, then ConcurrentHashMap promises that one of the two values will be associated with the key. i.e. if thread A runs map.put("Answers",2); and thread B runs map.put("Answers",10);, then ConcurrentHashMap will ensure that the map is valid and contains either 2 or 10 for "Answers", but it won't make any promises about which of those two it is.

这篇关于修改ConcurrentHashMap中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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