Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added try catch in computeifpresent to preserve old value incase of e… #5896

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,16 @@ public void testComputeEviction() {
assertThat(c.asMap().computeIfAbsent("hash-2", k -> "")).isEqualTo("");
}

public void testComputeIfPresent_error() {
Cache<String, String> cache = CacheBuilder.newBuilder().build();
cache.put(key, "1");
try {
cache.asMap().computeIfPresent(key, (key, value) -> { throw new Error(); });
} catch (Error e) {}
assertEquals("1", cache.getIfPresent(key));
assertEquals("2", cache.asMap().computeIfPresent(key, (k, v) -> "2"));
}

public void testComputeIfPresent() {
cache.put(key, "1");
// simultaneous update for same key, expect count successful updates
Expand Down
16 changes: 12 additions & 4 deletions guava/src/com/google/common/cache/LocalCache.java
Original file line number Diff line number Diff line change
Expand Up @@ -4223,7 +4223,17 @@ public V computeIfAbsent(K key, Function<? super K, ? extends V> function) {
public V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> function) {
checkNotNull(key);
checkNotNull(function);
return compute(key, (k, oldValue) -> (oldValue == null) ? null : function.apply(k, oldValue));
return compute(key, (k, oldValue) -> {
try{
if(oldValue==null){
return null;
}
return function.apply(k, oldValue);
}catch (Throwable e){
this.put(k,oldValue);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a bit sketchy, e.g. ConcurrentHashMap does not allow writes within a computation. I think it would be better to handle this within the compute method, even if a more complex method to understand.

throw e;
}
});
}

@Override
Expand Down Expand Up @@ -4907,9 +4917,7 @@ public long size() {
}

@Override
public ConcurrentMap<K, V> asMap() {
return localCache;
}
public ConcurrentMap<K, V> asMap() { return localCache; }

@Override
public CacheStats stats() {
Expand Down