001
014
015 package com.liferay.portal.cache.ehcache;
016
017 import com.liferay.portal.cache.mvcc.MVCCPortalCache;
018 import com.liferay.portal.kernel.cache.LowLevelCache;
019 import com.liferay.portal.model.MVCCModel;
020
021 import java.io.Serializable;
022
023 import net.sf.ehcache.Ehcache;
024 import net.sf.ehcache.Element;
025
026
029 public class LockBasedMVCCEhcachePortalCache
030 <K extends Serializable, V extends MVCCModel>
031 extends MVCCPortalCache<K, V> {
032
033 public LockBasedMVCCEhcachePortalCache(LowLevelCache<K, V> lowLevelCache) {
034 super(lowLevelCache);
035
036 if (!(lowLevelCache instanceof EhcachePortalCache)) {
037 throw new IllegalArgumentException(
038 "LowLevelCache is not a EhcachePortalCache");
039 }
040
041 EhcachePortalCache<?, ?> ehcachePortalCache =
042 (EhcachePortalCache<?, ?>)lowLevelCache;
043
044 _ehcache = ehcachePortalCache.ehcache;
045 }
046
047 @Override
048 public void remove(K key) {
049 _ehcache.acquireWriteLockOnKey(key);
050
051 try {
052 super.remove(key);
053 }
054 finally {
055 _ehcache.releaseWriteLockOnKey(key);
056 }
057 }
058
059 @Override
060 protected void doPut(K key, V value, int timeToLive, boolean quiet) {
061 if (key == null) {
062 throw new NullPointerException("Key is null");
063 }
064
065 if (value == null) {
066 throw new NullPointerException("Value is null");
067 }
068
069 if (timeToLive < 0) {
070 throw new IllegalArgumentException("Time to live is negative");
071 }
072
073 Element newElement = new Element(key, value);
074
075 if (timeToLive > 0) {
076 newElement.setTimeToLive(timeToLive);
077 }
078
079 _ehcache.acquireWriteLockOnKey(key);
080
081 try {
082 Element oldElement = _ehcache.get(key);
083
084 if (oldElement == null) {
085 _ehcache.put(newElement, quiet);
086
087 return;
088 }
089
090 V oldValue = (V)oldElement.getObjectValue();
091
092 if (value.getMvccVersion() <= oldValue.getMvccVersion()) {
093 return;
094 }
095
096 _ehcache.put(newElement, quiet);
097 }
098 finally {
099 _ehcache.releaseWriteLockOnKey(key);
100 }
101 }
102
103 private final Ehcache _ehcache;
104
105 }