Closed joerandazzo closed 1 year ago
And to be clearer, this is relating to setting the expiration policy to ACCESSED
Edit: If you do a map.get
while iterating on a keySet
with ExpirationPolicy.ACCESSED
you will get ConcurrentModificationException
since the get
can effectively modify the map by removing expired elements. Instead, use entrySet
:
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.printf("key:" + entry.getKey() + " val:" + entry.getValue());
}
Let me know if you still have problems.
Hello @jhalterman ,
Facing same error periodically in the following implementation.
Map<String, Object> map = ExpiringMap.builder().expiration(3600, TimeUnit.SECONDS).build(); List<Object> objList = new ArrayList<>(map.values());
Any Suggestion for the solution.
@MohdArshil Are you iterating over keys while attempting to modify the map? Or are you doing some other operations?
ConcurrentMap provides two contracts:
By throwing a ConcurrentModificationException on modification of a ConcurrentMap while iterating, you've broken the first contract. Broken Java contracts are why I have trust issues.
All joking aside, it would definitely be appreciated if we were able to modify (or iterate with expired values, in the case of #30 ) without getting unexpected exceptions. It was quite strange seeing a ConcurrentModificationException being thrown from a ConcurrentMap.
I've only glanced at some of the code and errors, but it looks like a lock or map copy may be needed when iterating. Possibly an expired value check before an iterator is given?
ExpiringMap doesn't implement the iterator, it obtains it from an underlying data structure, so it doesn't have the opportunity to coordinate writes to the map with iteration. So we'd possibly need to create and control our own iterator.
Happy to review a PR for this.
Of course! I'll take a closer look at the codebase and PR if I can get some time.
Woah, sorry for the push spam, didn't expect github to write every single one here...
This has been fixed in 0.5.11.
Hello,
I noticed an older issue reporting ConcurrentModificationException, and found the issue is still occurring in 0.4.2. I tried keyset and entrySet.