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.IOException; 021import java.io.Serializable; 022import java.util.concurrent.TimeUnit; 023 024import org.apache.commons.logging.Log; 025import org.apache.commons.logging.LogFactory; 026 027import com.google.common.cache.Cache; 028import com.google.common.cache.CacheBuilder; 029 030/** 031 * Default in memory implementation for cache management based on guava 032 * 033 * @since 6.0 034 */ 035public class InMemoryCacheImpl extends AbstractCache { 036 037 public InMemoryCacheImpl(CacheDescriptor desc) { 038 super(desc); 039 CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder(); 040 builder = builder.expireAfterWrite(desc.ttl, TimeUnit.MINUTES); 041 if (desc.options.containsKey("concurrencyLevel")) { 042 builder = builder.concurrencyLevel(Integer.valueOf(desc.options.get("concurrencyLevel")).intValue()); 043 } 044 if (desc.options.containsKey("maxSize")) { 045 builder = builder.maximumSize(Integer.valueOf(desc.options.get("maxSize")).intValue()); 046 } 047 cache = builder.build(); 048 } 049 050 protected static final Log log = LogFactory.getLog(InMemoryCacheImpl.class); 051 052 protected final Cache<String, Serializable> cache; 053 054 /** 055 * Get the instance cache 056 * 057 * @return the Guava instance cache used in this nuxeo cache 058 * @since 6.0 059 */ 060 public Cache<String, Serializable> getGuavaCache() { 061 return cache; 062 } 063 064 @Override 065 public Serializable get(String key) { 066 if (key == null) { 067 return null; 068 } else { 069 return cache.getIfPresent(key); 070 } 071 } 072 073 @Override 074 public void invalidate(String key) { 075 if (key != null) { 076 cache.invalidate(key); 077 } else { 078 log.warn(String.format("Can't invalidate a null key for the cache '%s'!", name)); 079 } 080 } 081 082 @Override 083 public void invalidateAll() { 084 cache.invalidateAll(); 085 } 086 087 @Override 088 public void put(String key, Serializable value) { 089 if (key != null && value != null) { 090 cache.put(key, value); 091 } else { 092 log.warn(String.format("Can't put a null key nor a null value in the cache '%s'!", name)); 093 } 094 } 095 096 @Override 097 public boolean hasEntry(String key) { 098 return cache.asMap().containsKey(key); 099 } 100 101}