`

Java Application Cache

    博客分类:
  • JDK
 
阅读更多
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));
	}
	
	
}


分享到:
评论

相关推荐

    cache java

    when use cache for a java application

    Programming.Google.App.Engine.with.Java

    The Memory Cache Chapter 13. Fetching URLs and Web Resources Chapter 14. Sending and Receiving Email Messages Chapter 15. Sending and Receiving Instant Messages with XMPP Chapter 16. Task Queues and ...

    源代码+书Java EE 8 High Performance

    Monitor your applicationsApplication optimization: memory management and server configurationScale up: threading and implicationsBe lazy, cache your dataBe fault tolerantLoggers and performances: a ...

    mmp-java:mmp-java Java和JEE开发框架

    mmp-application- cache-包含Java类和资源,这些类和资源提供基于Hazelcast的分布式内存中缓存功能。 mmp-application-kafka-包含支持使用Apache Kafka开发应用程序的Java类和资源。 mmp-application-messaging-...

    Java EE 8 High Performance

    Monitor your applicationsApplication optimization: memory management and server configurationScale up: threading and implicationsBe lazy, cache your dataBe fault tolerantLoggers and performances: a ...

    SimpleCache:用Java实现的缓存框架,使用HashMap进行存储,你可以实现Cache和CacheFactoryStrategy来自定义你的缓存实现逻辑

    SimpleCacheA Cache framework for java and android application, objects are store in key-value pair in memory,value can be any java object like String, List, Map etc. you can define your store logic ...

    html5应用缓存_动力节点Java学院整理

    什么是Application Cache HTML5引入了应用程序缓存技术,意味着web应用可进行缓存,并在没有网络的情况下使用,通过创建cache manifest文件,可以轻松的创建离线应用。 Application Cache带来的三个优势是: ① 离线...

    Springboot开发+Springmvc+Hibernate 在线招标系统源代码.zip

    Springboot+Springmvc+Hibernate 在线招标系统源代码.zip 如有部署疑问可私信联系 ... │ │ │ └── ApplicationCache.java │ │ ├── controller │ │ │ ├── BidController.java

    java 面试题 总结

    JAVA相关基础知识 1、面向对象的特征有哪些方面 1.抽象: 抽象就是忽略一个主题中与当前目标无关的那些方面,以便更充分地注意与当前目标有关的方面。抽象并不打算了解全部问题,而只是选择其中的一部分,暂时不用...

    RESTful-API后台系统架构设计(Java).doc

    AOP Framework Logback - Logging API SLF4J - Logging API Abstraction 其它: Application Server - JBoss AS Distributed Cache - EHCache 上图可以看出,前端入口是负载均衡和反向代理(Apache HTTPD with mod_...

    ASP javascript Application对象的Contents和StaticObjects做Cache的一些经验

    Application对象内置集合有为存放简单类型设计的Contents,默认Application(“key”)就可以使用。 不过Application.Contents不能存放对象,可以存vbs数组,但是在javascript下甚至数组都不能放。 使用Application....

    ace-java-demo:Java ace演示

    ACE Java Demo ApplicationDemo应用,演示ACE的功能:ACE服务的使用Cache服务(缓存)Store服务(文件存储)Log服务(收集日志在ACE控制台上查看)Mail服务(发送邮件)ACE环境配置的读取WebSocket使用代码如何使用...

    cordova-plugin-clearcache:清除应用程序缓存

    Clear Application Cache Install cordova plugin add Use getCaches 获取应用缓存大小 navigator.clearCache.getCaches(function (result) { // 获取成功回调方法 // result - 缓存大小,单位Bytes }); ...

    danajia-java:达那加Java

    ACE Java Demo ApplicationDemo应用,演示ACE的功能:ACE服务的使用Cache服务(缓存)Store服务(文件存储)Log服务(收集日志在ACE控制台上查看)Mail服务(发送邮件)ACE环境配置的读取WebSocket使用代码如何使用...

    SpCache:SharedPreferences 的缓存库

    public class SpCacheApplication extends Application { @Override public void onCreate () { super . onCreate(); SpCache . init( this ); } } 然后就可以自由使用啦~~ 使用 SpCache.putXXX() 和 Sp...

    Java毕业设计,SpringBoot+MySQL+Layui实现的在线考试系统源码.zip

    一个 JAVA 实现的在线考试系统,主要实现一套基于不同类型的客观题,进行自动组卷、批卷等功能的考试系统(没有主观题) 在线演示:http://120.24.242.142:8080/index 学生账号:111/12345 教师账号:000/12345 ...

    《Velocity1.4 java开发指南》中文版

    8.Application Attributes 17 9.EventCartridge and Event Handlers(事件分发和处理) 17 1.Event Handlers 17 2.Using the EventCartridge使用事件分发器 18 10.Velocity Configuration Keys and Values(配置参数...

    简易聊天室

    简易聊天室本次实验的目的是通过以下题目掌握JSP内置对象,包括:request,response,session,application等。 (1)制作简易聊天室,能够实现简单的页面聊天功能。 (2)制作网页计数器,要求相同的窗口内刷新页面访问...

    超级有影响力霸气的Java面试题大全文档

    超级有影响力的Java面试题大全文档 1.抽象: 抽象就是忽略一个主题中与当前目标无关的那些方面,以便更充分地注意与当前目标有关的方面。抽象并不打算了解全部问题,而只是选择其中的一部分,暂时不用部分细节。...

    基于Java开发的员工考勤管理系统源码-Web版+数据库sql+项目说明+设计报告.zip

    基于Java开发的员工考勤管理系统源码-Web版+数据库sql+项目说明+设计报告.zip 【资源介绍】 该项目是个人毕设项目,答辩... npm config set cache "node-repos/cache" npm config set prefix "node-repos/prefix" ```

Global site tag (gtag.js) - Google Analytics