String cacheName = cacheName(key, metadata.getCacheGroups());
// create empty cache for cache group here, as we have a factory to
// create an object, and should never ever return null from this
// method.
Ehcache cache = cacheManager.addCacheIfAbsent(cacheName);
Element result = cache.get(key);
if (result != null) {
return (List) result.getObjectValue();
}
// if no result in cache locking the key to write
// and putting it to the cache
cache.acquireWriteLockOnKey(key);
try {
// now that we locked the key, let's reread the cache again, in case
// an object appeared there already
result = cache.get(key);
if (result != null) {
return (List) result.getObjectValue();
}
// if not succeeded in reading again putting
// object to the cache ourselves
Object object = factory.createObject();
if (!(object instanceof List)) {
if (object == null) {
throw new CayenneRuntimeException("Null object created: " + metadata.getCacheKey());
} else {
throw new CayenneRuntimeException("Invalid query result, expected List, got "
+ object.getClass().getName());
}
}
cache.put(new Element(key, object));
return (List) object;
} finally {
cache.releaseWriteLockOnKey(key);
}
}