`

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));
	}
	
	
}


分享到:
评论

相关推荐

    Oracle 9i Java程序设计—使用PL_SQL和Java的解决方案

    3. **Java Application Cache**:Oracle 9i提供了一个Java应用程序缓存,可以在数据库级别存储和共享数据,提高了应用程序的性能。 4. **JDBC(Java Database Connectivity)**:Oracle 9i优化了JDBC驱动,提供了...

    springboot整合jetcache完整代码

    配置完成后,你需要在SpringBoot的配置文件(application.yml或application.properties)中设置JetCache的相关参数。例如,如果你想使用Redis作为缓存后端,可以这样配置: ```yaml jetcache: local: limit: ...

    cache设置缓存数据,可直接运行

    5. **CacheApplication.java**:这是Spring Boot应用的主类,通常包含`@SpringBootApplication`注解,启动整个应用。可能还包含了一些初始化逻辑,如配置缓存或者启动时的其他自定义操作。 6. **缓存策略**:在Java...

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

    http://localhost/applicationcache/zepto.js NETWORK: 4.jpg FALLBACK: *.html /offline.html 2.jpg /3.jpg ``` 上述`manifest`文件分为三部分: 1. `CACHE`:列出需要缓存的文件。 2. `NETWORK`:列出需要在...

    更简单的Java缓存框架 jscache.docx

    ### 更简单的Java缓存框架 jscache #### 知识点概述 jscache是一个轻量级、易用的Java缓存框架,它基于面向切面编程(AOP)原理实现,支持灵活配置缓存策略,并提供了多种缓存实现方式。通过使用jscache,开发者...

    阿里开源的缓存框架JetCache.pdf

    然后,在application.properties文件中配置JetCache的相关参数: ```properties jetcache.remote.default.valueDecoder = java jetcache.remote.default.keyConvertor = fastjson jetcache.areaInCacheName = false...

    springboot1.x基于spring注解实现J2Cache两级缓存集成

    配置Redis连接并启用J2Cache的Redis支持,我们可以在`application.properties`中添加以下内容: ``` spring.redis.host=localhost spring.redis.port=6379 j2cache.cacheManager.type=redis ``` 在使用J2Cache的...

    springcache+redis springboot maven

    2. 配置Redis:在`application.properties`或`application.yml`中配置Redis连接信息,包括地址、端口、密码等。 ```properties spring.redis.host=localhost spring.redis.port=6379 ``` 3. 创建RedisCacheManager...

    java直播推流

    add_header Cache-Control no-cache; types { application/vnd.apple.mpegurl m3u8; video/mp4 ts; } default_type application/vnd.apple.mpegurl; } } } ``` HTML5的`&lt;video&gt;`标签支持HLS流播放,只需...

    Redis整合SpringCache实例

    **Redis整合SpringCache实例** 在现代的Web应用中,数据缓存是提高系统性能的关键技术之一。本示例主要探讨如何将开源的内存数据结构存储系统Redis与Spring Cache框架结合,实现高效的分布式缓存解决方案。Redis以...

    Java Spring Boot application for currency conversion

    综上所述,这个“Java Spring Boot application for currency conversion”项目涵盖了Spring MVC框架的使用、单元测试的实践以及测试结果的可视化,体现了良好的软件工程原则和最佳实践。无论是对初学者还是经验丰富...

    hibernate_cache_level_2.rar_java_staredb4u

    这包括选择合适的缓存提供商,比如EhCache,然后在Hibernate的配置文件(hibernate.cfg.xml或application.properties)中启用二级缓存并指定对应的缓存策略。例如: ```xml &lt;property name="hibernate.cache.use_...

    spring-cache(通过key值更新缓存)

    7. **事件监听**:Spring Cache还支持缓存事件监听,通过实现`ApplicationListener&lt;CacheEvictedEvent&gt;`等接口,可以在缓存操作后执行相应的逻辑。 8. **异常处理**:当方法抛出异常时,Spring Cache可以配置是否将...

    bootj2cache.rar

    首先,J2Cache是一款轻量级的Java缓存框架,它支持多级缓存策略,可以方便地与其他缓存实现如Ehcache和Redis结合使用。Ehcache作为一级缓存,主要用于本地快速访问,而Redis作为二级缓存,用于跨服务器的数据共享和...

    websphere缓存java调用以及jar包

    标题中的“websphere缓存java调用以及jar包”指的是在IBM WebSphere Application Server (WAS) 中使用Java编程方式来管理和操作缓存系统。WebSphere应用服务器提供了一种高效的方式来存储和检索频繁访问的数据,以...

    springboot 使用spring cache缓存 和 使用fastjson配置redis系列化

    接下来,配置文件`application.yml`中,我们可以使用Redis的默认配置,如果需要自定义配置,例如连接池、密码等,可以按需添加。 在应用中启用Spring Cache,我们需要创建一个配置类,该类使用`@EnableCaching`注解...

    源代码+书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-...

Global site tag (gtag.js) - Google Analytics