Skip to content

Commit

Permalink
Use the readLock when creating an Iterator for the Map.
Browse files Browse the repository at this point in the history
This is an addition to the fix implemented with #78 which did not cover all cases.
  • Loading branch information
bratkartoffel committed Dec 5, 2023
1 parent 93973e5 commit 228290b
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 2 deletions.
9 changes: 7 additions & 2 deletions src/main/java/net/jodah/expiringmap/ExpiringMap.java
Original file line number Diff line number Diff line change
Expand Up @@ -714,8 +714,13 @@ public boolean contains(Object entry) {

@Override
public Iterator<Map.Entry<K, V>> iterator() {
return (entries instanceof EntryLinkedHashMap) ? ((EntryLinkedHashMap<K, V>) entries).new EntryIterator()
: ((EntryTreeHashMap<K, V>) entries).new EntryIterator();
readLock.lock();
try {
return (entries instanceof EntryLinkedHashMap) ? ((EntryLinkedHashMap<K, V>) entries).new EntryIterator()
: ((EntryTreeHashMap<K, V>) entries).new EntryIterator();
} finally {
readLock.unlock();
}
}

@Override
Expand Down
36 changes: 36 additions & 0 deletions src/test/java/net/jodah/expiringmap/issues/Issue10.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,15 @@
import org.testng.Assert;
import org.testng.annotations.Test;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
* Do not throw ConcurrentModificationException when using an Iterator
Expand Down Expand Up @@ -55,4 +61,34 @@ public void testKeySet() {
Assert.assertEquals((Integer) 3, iterator.next());
}
}

public void testParallelPutRemove() {
ExpiringMap<Integer, String> testee = ExpiringMap.create();
ExecutorService service = Executors.newFixedThreadPool(2);

Runnable adder = () -> {
ThreadLocalRandom rnd = ThreadLocalRandom.current();
AtomicInteger counter = new AtomicInteger(0);
for (int j = 0; j < 5; j++) {
for (int i = 0; i < 100_000; i++) {
if (rnd.nextBoolean()) {
testee.put(counter.incrementAndGet(), "bar");
}
}
}
};

Runnable remover = () -> {
while (!service.isTerminated()) {
List<Integer> entriesToDelete = new ArrayList<>();
for (Map.Entry<Integer, String> e : testee.entrySet()) {
entriesToDelete.add(e.getKey());
}
entriesToDelete.forEach(testee.keySet()::remove);
}
};
service.submit(adder);
service.shutdown(); // schedule shutdown, let the running tasks finish
remover.run(); // run synchronous, waits for the adder threads to finish
}
}

0 comments on commit 228290b

Please sign in to comment.