Skip to content

Commit

Permalink
Merge pull request #87 from bratkartoffel/bugfix/gh10-additional-read…
Browse files Browse the repository at this point in the history
…Lock

Use the readLock when creating an Iterator for the Map.
  • Loading branch information
jhalterman authored Jan 25, 2025
2 parents 93973e5 + 228290b commit f45f3f0
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 f45f3f0

Please sign in to comment.