Java Application Cache

本文探讨了应用程序缓存的管理策略,特别是使用软引用实现内存敏感型缓存的方法。通过实例展示了如何利用软引用和ConcurrentHashMap来构建高效且可控的应用程序缓存。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值