001    /**
002     * Copyright (c) 2000-present Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portal.cache.mvcc;
016    
017    import com.liferay.portal.kernel.cache.LowLevelCache;
018    import com.liferay.portal.kernel.cache.PortalCacheWrapper;
019    import com.liferay.portal.model.MVCCModel;
020    
021    import java.io.Serializable;
022    
023    /**
024     * @author Shuyang Zhou
025     */
026    public class MVCCPortalCache<K extends Serializable, V extends MVCCModel>
027            extends PortalCacheWrapper<K, V> {
028    
029            public MVCCPortalCache(LowLevelCache<K, V> lowLevelCache) {
030                    super(lowLevelCache);
031    
032                    _lowLevelCache = lowLevelCache;
033            }
034    
035            @Override
036            public void put(K key, V value) {
037                    put(key, value, DEFAULT_TIME_TO_LIVE);
038            }
039    
040            @Override
041            public void put(K key, V value, int timeToLive) {
042                    while (true) {
043                            V oldValue = _lowLevelCache.get(key);
044    
045                            if (oldValue == null) {
046                                    oldValue = _lowLevelCache.putIfAbsent(key, value, timeToLive);
047    
048                                    if (oldValue == null) {
049                                            return;
050                                    }
051                            }
052    
053                            if (value.getMvccVersion() <= oldValue.getMvccVersion()) {
054                                    return;
055                            }
056    
057                            if (_lowLevelCache.replace(key, oldValue, value, timeToLive)) {
058                                    return;
059                            }
060                    }
061            }
062    
063            private final LowLevelCache<K, V> _lowLevelCache;
064    
065    }