ConcurrentHashMap 可以一边遍历一边修改吗
时间: 2023-12-08 12:38:59 浏览: 80
java哈希遍历_哈希遍历_
是的,ConcurrentHashMap可以一边遍历一边修改。这是因为ConcurrentHashMap内部使用了一种叫做分段锁(Segment)的机制,将整个Map分成了多个小的Segment,每个Segment内部都有一个锁。在进行修改操作时,只需要锁住当前需要修改的Segment,而不是整个Map,这样就可以实现并发修改而不会出现线程安全问题。而在进行遍历操作时,只需要获取每个Segment的锁,就可以同时遍历整个Map,而不会出现ConcurrentModificationException等异常。
以下是一个演示代码:
```python
from concurrent.futures import ThreadPoolExecutor
import time
import random
import string
from collections.abc import MutableMapping
class ConcurrentHashMap(MutableMapping):
def __init__(self, *args, **kwargs):
self._lock = ThreadPoolExecutor(max_workers=1)
self._segments = [{} for _ in range(16)]
self.update(dict(*args, **kwargs))
def __getitem__(self, key):
segment = self._get_segment(key)
with self._lock:
return segment[key]
def __setitem__(self, key, value):
segment = self._get_segment(key)
with self._lock:
segment[key] = value
def __delitem__(self, key):
segment = self._get_segment(key)
with self._lock:
del segment[key]
def __iter__(self):
with self._lock:
for segment in self._segments:
yield from segment.keys()
def __len__(self):
with self._lock:
return sum(len(segment) for segment in self._segments)
def _get_segment(self, key):
return self._segments[hash(key) % len(self._segments)]
# 测试代码
def test_concurrent_modify():
d = ConcurrentHashMap()
for i in range(100):
d[i] = ''.join(random.choices(string.ascii_uppercase + string.digits, k=10))
def modify():
for i in range(100):
d[i] = ''.join(random.choices(string.ascii_uppercase + string.digits, k=10))
def iterate():
for k, v in d.items():
pass
with ThreadPoolExecutor(max_workers=2) as executor:
executor.submit(modify)
executor.submit(iterate)
print('ConcurrentHashMap can modify and iterate concurrently.')
test_concurrent_modify()
```
阅读全文