Skip to content

Commit

Permalink
apacheGH-2802: Remove only if same key
Browse files Browse the repository at this point in the history
  • Loading branch information
afs committed Oct 28, 2024
1 parent c58b1cb commit 20d9c7e
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 10 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -115,19 +115,14 @@ public V get(K key, Function<K, V> function) {
}
}


@Override
public void put(K key, V thing) {
Objects.requireNonNull(key);
final int idx = calcIndex(key);
if(thing == null) { //null value causes removal of entry
if (keys[idx] != null) {
keys[idx] = null;
values[idx] = null;
currentSize--;
}
if (thing == null) {
remove(key);
return;
}
final int idx = calcIndex(key);
if(!thing.equals(values[idx])) {
values[idx] = thing;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public class TestCacheSimple {

/**
* Simple test to ensure that {@link CacheSimple} evidences
* the fixed-size behavior we desire.
* the fixed-size behaviour we desire.
*/
@Test
public void testFixedSize() {
Expand Down Expand Up @@ -208,6 +208,24 @@ public void testRemove() {
}
}

@Test
public void testRemoveSameHash() {
CompoundKey key1 = new CompoundKey(1, 1);
CompoundKey key2 = new CompoundKey(1, 2);
String value1 = "v1";
String value2 = "v2";

Cache<CompoundKey, String> cache = new CacheSimple<>(10);

cache.put(key1, value1);
// Delete - different key
cache.put(key2, null);
String s = cache.getIfPresent(key1);

assertEquals(1, cache.size());
assertEquals(value1, s);
}

@Test
public void testGet() {
Cache<String, String> cache = new CacheSimple<>(10);
Expand Down Expand Up @@ -325,7 +343,7 @@ public void testAllocatedSize() {
assertEquals(16, cache.getAllocatedSize());
}

// Compound key for tests.
// Compound key for tests.
private static final class CompoundKey {
private final int a;
private final int b;
Expand Down

0 comments on commit 20d9c7e

Please sign in to comment.