001/* 002 * (C) Copyright 2014 Nuxeo SA (http://nuxeo.com/) and others. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 * 016 * Contributors: 017 * Maxime Hilaire 018 * 019 */ 020package org.nuxeo.ecm.core.cache; 021 022import java.io.Serializable; 023import java.util.concurrent.TimeUnit; 024 025import org.apache.commons.logging.Log; 026import org.apache.commons.logging.LogFactory; 027 028import com.google.common.cache.Cache; 029import com.google.common.cache.CacheBuilder; 030 031/** 032 * Default in memory implementation for cache management based on guava 033 * 034 * @since 6.0 035 */ 036public class InMemoryCacheImpl extends AbstractCache { 037 038 public InMemoryCacheImpl(CacheDescriptor desc) { 039 super(desc); 040 CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder(); 041 builder = builder.expireAfterWrite(desc.ttl, TimeUnit.MINUTES); 042 if (desc.options.containsKey("concurrencyLevel")) { 043 builder = builder.concurrencyLevel(Integer.valueOf(desc.options.get("concurrencyLevel")).intValue()); 044 } 045 if (desc.options.containsKey("maxSize")) { 046 builder = builder.maximumSize(Integer.valueOf(desc.options.get("maxSize")).intValue()); 047 } 048 cache = builder.build(); 049 } 050 051 protected static final Log log = LogFactory.getLog(InMemoryCacheImpl.class); 052 053 protected final Cache<String, Serializable> cache; 054 055 /** 056 * Get the instance cache 057 * 058 * @return the Guava instance cache used in this nuxeo cache 059 * @since 6.0 060 */ 061 public Cache<String, Serializable> getGuavaCache() { 062 return cache; 063 } 064 065 @Override 066 public Serializable get(String key) { 067 if (key == null) { 068 return null; 069 } else { 070 return cache.getIfPresent(key); 071 } 072 } 073 074 @Override 075 public void invalidate(String key) { 076 if (key != null) { 077 cache.invalidate(key); 078 } else { 079 log.warn(String.format("Can't invalidate a null key for the cache '%s'!", name)); 080 } 081 } 082 083 @Override 084 public void invalidateAll() { 085 cache.invalidateAll(); 086 } 087 088 @Override 089 public void put(String key, Serializable value) { 090 if (key != null && value != null) { 091 cache.put(key, value); 092 } else { 093 log.warn(String.format("Can't put a null key nor a null value in the cache '%s'!", name)); 094 } 095 } 096 097 @Override 098 public boolean hasEntry(String key) { 099 return cache.asMap().containsKey(key); 100 } 101 102}