Search code examples
javaspringspring-bootehcacheconcurrentmodification

ConcurrentModification EHCache Multi Thread Java


we have multiple threads trying to get from EHCache and this sometimes causes concurrencymodification exceptions. I tried Retryable to address this issue but it doesn't seem to be doing anything. Any suggestions?

@Override
@Retryable(include= ConcurrentModificationException.class, backoff = @Backoff(delay = 5000, maxDelay = 3000), maxAttempts = 5)
public Object getFromCache(String cacheDomain, String cacheKey) {
    Object value = null;
    Cache cacheObject = getCacheObject();
    if (cacheObject != null) {
        StringBuilder fullCacheKey = new StringBuilder();
        fullCacheKey.append(cacheDomain);
        fullCacheKey.append("|");
        fullCacheKey.append(cacheKey);
        synchronized (cacheObject) {
            Element cacheElement = cacheObject.get(fullCacheKey.toString());
            if (cacheElement != null) {
                value = cacheElement.getObjectValue();
            }
        }
        log.debug("Value from Cache with key [" + fullCacheKey.toString() + "] is " + value);
    }
    return value;
}

Solution

  • I'm doing a deep copy in the method to prevent this error now. Might this have any unforeseen consequences? The method would only ever get from the cache so I believe there would be no repercussions

    Element cacheElement = (Element) SerializationUtils.clone(cacheObject.get(fullCacheKey.toString()));