Skip to content

Instantly share code, notes, and snippets.

@bivas
Created September 6, 2011 07:09
Show Gist options
  • Save bivas/1196809 to your computer and use it in GitHub Desktop.
Save bivas/1196809 to your computer and use it in GitHub Desktop.
EhCache event listener for preventing caching of null values in data store
<cache name="myNonNullCache"
<!-- cache configuration -->
>
<cacheEventListenerFactory class="com.example.cache.NotNullCacheEventListenerFactory" />
</cache>
package com.example.cache;
import net.sf.ehcache.CacheException;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;
import net.sf.ehcache.event.CacheEventListener;
final class NotNullCacheEventListener implements CacheEventListener {
public static final CacheEventListener INSTANCE = new NotNullCacheEventListener();
@Override
public void notifyElementRemoved(final Ehcache cache, final Element element) throws CacheException {
}
@Override
public void notifyElementPut(final Ehcache cache, final Element element) throws CacheException {
removeIfNull(cache, element);
}
@Override
public void notifyElementUpdated(final Ehcache cache, final Element element) throws CacheException {
removeIfNull(cache, element);
}
private void removeIfNull(final Ehcache cache, final Element element) {
if (element.getObjectValue() == null) {
cache.remove(element.getKey());
}
}
@Override
public void notifyElementExpired(final Ehcache cache, final Element element) {
}
@Override
public void notifyElementEvicted(final Ehcache cache, final Element element) {
}
@Override
public void notifyRemoveAll(final Ehcache cache) {
}
@Override
public void dispose() {
}
@Override
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException("Singleton instance");
}
}
package com.example.cache;
import java.util.Properties;
import net.sf.ehcache.event.CacheEventListener;
import net.sf.ehcache.event.CacheEventListenerFactory;
public class NotNullCacheEventListenerFactory extends CacheEventListenerFactory {
@Override
public CacheEventListener createCacheEventListener(final Properties properties) {
return NotNullCacheEventListener.INSTANCE;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment