001/* 002 * (C) Copyright 2014 Nuxeo SAS (http://nuxeo.com/) and contributors. 003 * 004 * All rights reserved. This program and the accompanying materials 005 * are made available under the terms of the GNU Lesser General Public License 006 * (LGPL) version 2.1 which accompanies this distribution, and is available at 007 * http://www.gnu.org/licenses/lgpl-2.1.html 008 * 009 * This library is distributed in the hope that it will be useful, 010 * but WITHOUT ANY WARRANTY; without even the implied warranty of 011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 012 * Lesser General Public License for more details. 013 * 014 * Contributors: 015 * Maxime Hilaire 016 * 017 */ 018package org.nuxeo.ecm.core.cache; 019 020import java.io.Serializable; 021import java.util.concurrent.TimeUnit; 022 023import org.apache.commons.logging.Log; 024import org.apache.commons.logging.LogFactory; 025 026import com.google.common.cache.Cache; 027import com.google.common.cache.CacheBuilder; 028 029/** 030 * Default in memory implementation for cache management based on guava 031 * 032 * @since 6.0 033 */ 034public class InMemoryCacheImpl extends AbstractCache { 035 036 public InMemoryCacheImpl(CacheDescriptor desc) { 037 super(desc); 038 CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder(); 039 builder = builder.expireAfterWrite(desc.ttl, TimeUnit.MINUTES); 040 if (desc.options.containsKey("concurrencyLevel")) { 041 builder = builder.concurrencyLevel(Integer.valueOf(desc.options.get("concurrencyLevel")).intValue()); 042 } 043 if (desc.options.containsKey("maxSize")) { 044 builder = builder.maximumSize(Integer.valueOf(desc.options.get("maxSize")).intValue()); 045 } 046 cache = builder.build(); 047 } 048 049 protected static final Log log = LogFactory.getLog(InMemoryCacheImpl.class); 050 051 protected final Cache<String, Serializable> cache; 052 053 /** 054 * Get the instance cache 055 * 056 * @return the Guava instance cache used in this nuxeo cache 057 * @since 6.0 058 */ 059 public Cache<String, Serializable> getGuavaCache() { 060 return cache; 061 } 062 063 @Override 064 public Serializable get(String key) { 065 if (key == null) { 066 return null; 067 } else { 068 return cache.getIfPresent(key); 069 } 070 } 071 072 @Override 073 public void invalidate(String key) { 074 if (key != null) { 075 cache.invalidate(key); 076 } else { 077 log.warn(String.format("Can't invalidate a null key for the cache '%s'!", name)); 078 } 079 } 080 081 @Override 082 public void invalidateAll() { 083 cache.invalidateAll(); 084 } 085 086 @Override 087 public void put(String key, Serializable value) { 088 if (key != null && value != null) { 089 cache.put(key, value); 090 } else { 091 log.warn(String.format("Can't put a null key nor a null value in the cache '%s'!", name)); 092 } 093 } 094 095 @Override 096 public boolean hasEntry(String key) { 097 return cache.asMap().containsKey(key); 098 } 099 100}