we need to cache user/business information in application, cause of it is used often, so don't need to clear cache.
sure, we can control of it, but if we cache so many messages, we will be lose control. every business want to cache something to improve it's performance, so what's the solution?
we can use soft reference, it will be GC before out of memory, and it used cache in so many cache framework.
package com.statestreet.tlp.cache; import java.lang.ref.SoftReference; import java.util.Collections; import java.util.concurrent.ConcurrentHashMap; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * * Common cache use scenarios include an application cache, a second level (L2)[EHCache] cache and a hybrid cache. * * * Global Cache.[Application Cache] * * Strong ==> Soft ==> Weak ==> Phantom * * SoftReference: Soft references are most often used to implement memory-sensitive caches * Soft reference objects, which are cleared at the discretion of the garbage collector in response to memory demand. * * WeakHashMap: the key is not usually use will be delete, there map is not synchronized {@link Collections#synchronizedMap Collections.synchronizedMap}. * case of back thread delete object don't use, so it is not used abroad * PhantomReference: garbage collector will be delete object, phantom reference always returnsnull
. * almost we can't see this example. * * * @author e557400 * */ public class GlobalCache { protected final Log log = LogFactory.getLog(GlobalCache.class); private static final GlobalCache gc = new GlobalCache(); /** * Application Cache don't clear, until we call. */ private ConcurrentHashMap> cache = new ConcurrentHashMap >(); private ConcurrentHashMap cachehitCount = new ConcurrentHashMap (); private GlobalCache(){ } public void clear(){ cache.clear(); cachehitCount.clear(); } public static GlobalCache getInstance(){ return gc; } /** * Thread-safe cache put. * * cache get method is not thread-safe, invalidate by other thread. * but map.putIfAbsent() which is atomic and therefore thread-safe. * * @param key key with which the specified value is to be associated * @param value value to be associated with the specified key * @return the previous value associated with the specified key, * or null if there was no mapping for the key */ public Object put(CacheKey key, Object value) { if(value == null){ throw new IllegalArgumentException("put GlobalCache value can't be null"); } Object ret = get(key); if (value != ret) { if(log.isDebugEnabled()){ if(ret == null){ log.debug("put new Cache( key["+key+"], value["+value+"] )"); }else{ log.error("attempt to override Cache( key["+key+"], old value["+ret+"] to value["+value+"] ), but will be failed."); } } ret = cache.putIfAbsent(key, new SoftReference