Java Application Cache

Application Cache is used very wide.

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 returns <code>null</code>.
 *              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<CacheKey, SoftReference<Object>> cache = new ConcurrentHashMap<CacheKey, SoftReference<Object>>();
	
	private ConcurrentHashMap<CacheKey, Integer> cachehitCount = new ConcurrentHashMap<CacheKey, Integer>();
	
	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 <tt>null</tt> 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<Object>(value));//if already associated with special key, no override.
	        if (ret == null) {
	            ret = value;
	        }
	    }
	    return ret;
	}
	
	/**
	 * ConcurrentHashMap call get method will be get segent lock
	 * 
	 * @param key
	 * @return
	 */
	public Object get(CacheKey key){ 
		Object value = null;
		SoftReference<Object> valueref = cache.get(key);
		
		if(valueref != null){
			value = valueref.get();
			if(value == null){ // If the value has been garbage collected, remove the entry from the HashMap.
				cache.remove(key);
			}
		}
		
		// log cache and monitor.
		if(log.isDebugEnabled()){
			Integer count = cachehitCount.get(key);
			if(count == null){
				count = 1;
			}
			if(valueref != null){
				log.debug("cache hit key["+key+"], count["+count+"]");
				count ++;
				cachehitCount.put(key, count);
			}
		}
		return value;
	}
	 
	/**
	 * wrap
	 * @param key
	 * @param value
	 * @return
	 */
	public Object put(String key, Object value){
		return put(new CacheKey(key),value);
	}
	/**
	 * value
	 * @param value
	 * @return
	 */
	public Object get(String key){
		return get(new CacheKey(key));
	}
	
	
}


猜你喜欢

转载自a123159521.iteye.com/blog/2283774
今日推荐