Skip to content

Commit

Permalink
Implement Iterator#remove for Cache values iter (#29633)
Browse files Browse the repository at this point in the history
This commit implements the ability to remove values from a Cache using
the values iterator. This brings the values iterator in line with the
keys iterator and adds support for removing items in the cache that are
not easily found by the key used for the cache.
  • Loading branch information
jaymode authored Apr 20, 2018
1 parent 42d81a2 commit dfc7ca7
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -580,7 +580,8 @@ public void remove() {

/**
* An LRU sequencing of the values in the cache. This sequence is not protected from mutations
* to the cache. The result of iteration under mutation is undefined.
* to the cache (except for {@link Iterator#remove()}. The result of iteration under any other mutation is
* undefined.
*
* @return an LRU-ordered {@link Iterable} over the values in the cache
*/
Expand All @@ -597,6 +598,11 @@ public boolean hasNext() {
public V next() {
return iterator.next().value;
}

@Override
public void remove() {
iterator.remove();
}
};
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
Expand Down Expand Up @@ -824,4 +825,34 @@ public void testTorture() throws BrokenBarrierException, InterruptedException {
cache.refresh();
assertEquals(500, cache.count());
}

public void testRemoveUsingValuesIterator() {
final List<RemovalNotification<Integer, String>> removalNotifications = new ArrayList<>();
Cache<Integer, String> cache =
CacheBuilder.<Integer, String>builder()
.setMaximumWeight(numberOfEntries)
.removalListener(removalNotifications::add)
.build();

for (int i = 0; i < numberOfEntries; i++) {
cache.put(i, Integer.toString(i));
}

assertThat(removalNotifications.size(), is(0));
final List<String> expectedRemovals = new ArrayList<>();
Iterator<String> valueIterator = cache.values().iterator();
while (valueIterator.hasNext()) {
String value = valueIterator.next();
if (randomBoolean()) {
valueIterator.remove();
expectedRemovals.add(value);
}
}

assertEquals(expectedRemovals.size(), removalNotifications.size());
for (int i = 0; i < expectedRemovals.size(); i++) {
assertEquals(expectedRemovals.get(i), removalNotifications.get(i).getValue());
assertEquals(RemovalNotification.RemovalReason.INVALIDATED, removalNotifications.get(i).getRemovalReason());
}
}
}

0 comments on commit dfc7ca7

Please sign in to comment.