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 null.
 *              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(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 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));
	}
	
	
}


 

                            
                        
                    
                    
                    

你可能感兴趣的:(Java Application Cache)