+ optimize updating of multiple caches



git-svn-id: https://src.springframework.org/svn/spring-framework/trunk@3822 50f2f4bb-b051-0410-bef5-90022cba6387
This commit is contained in:
Costin Leau 2010-12-17 09:14:09 +00:00
parent 4c8186f2a9
commit 637ce79d9e
1 changed files with 46 additions and 8 deletions

View File

@ -20,6 +20,7 @@ import java.io.Serializable;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.Iterator;
import java.util.Set; import java.util.Set;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
@ -167,14 +168,47 @@ public abstract class CacheAspectSupport implements InitializingBean {
if (context.hasConditionPassed()) { if (context.hasConditionPassed()) {
// check operation // check operation
if (cacheDef instanceof CacheUpdateDefinition) { if (cacheDef instanceof CacheUpdateDefinition) {
// for each cache Object key = context.generateKey();
// check cache first
for (Cache cache : caches) { //
Object key = context.generateKey(); // check usage of single cache
retVal = cache.get(key); // very common case which allows for some optimization
if (retVal == null) { // in exchange for code readability
//
if (caches.size() == 1) {
Cache cache = caches.iterator().next();
if (cache.containsKey(key)) {
retVal = cache.get(key);
} else {
retVal = invocation.call(); retVal = invocation.call();
cache.put(key, (retVal == null ? NULL_RETURN : retVal)); cache.put(key, retVal);
}
}
//
// multi cache path
//
else {
// for each cache
boolean cacheHit = false;
for (Iterator<Cache<?,?>> iterator = caches.iterator(); iterator.hasNext() && !cacheHit;) {
Cache cache = iterator.next();
if (cache.containsKey(key)){
retVal = cache.get(key);
cacheHit = true;
}
}
if (!cacheHit) {
retVal = invocation.call();
}
// update all caches (if needed)
for (Cache cache : caches) {
cache.putIfAbsent(key, retVal);
} }
} }
} }
@ -184,6 +218,8 @@ public abstract class CacheAspectSupport implements InitializingBean {
retVal = invocation.call(); retVal = invocation.call();
// for each cache // for each cache
// lazy key initialization
Object key = null;
for (Cache cache : caches) { for (Cache cache : caches) {
// flush the cache (ignore arguments) // flush the cache (ignore arguments)
@ -191,7 +227,9 @@ public abstract class CacheAspectSupport implements InitializingBean {
cache.clear(); cache.clear();
} else { } else {
// check key // check key
Object key = context.generateKey(); if (key == null) {
key = context.generateKey();
}
cache.remove(key); cache.remove(key);
} }
} }