java 内存table_java hashtable实现内存缓存

本文介绍了一个使用Java编写的缓存管理类,通过Hashtable实现缓存,提供putCache方法根据给定秒数设置过期时间,并通过validate方法检查缓存是否过期。核心代码展示了如何使用Calendar来管理缓存更新时间。
摘要由CSDN通过智能技术生成

直接上代码

public class CacheCode {

private static Hashtable cachMap = new Hashtable();

//重写载入缓存信息方法

public static void putCache(String key,Object obj){

putCache(key,obj,1800);//默认半小时

}

//重写载入缓存信息方法

public static void putCache(String key,Object obj,int seconds){

Cache cache = new Cache();

cache.setKey(key);

Calendar nowTime = Calendar.getInstance();

nowTime.add(Calendar.SECOND, seconds);

cache.setTimeOut(nowTime.getTimeInMillis()/1000);

cache.setValue(obj);

cachMap.put(key,cache);

}

//获取缓存信息

public static Object getCache(String key) {

Cache cache = cachMap.get(key);

if (cache != null) { //调用判断是否终止方法

if(validate(cache)){

return cache.getValue();

}else{

cachMap.remove(key);

}

}

return null;

}

//判断缓存是否有效

private static boolean validate(Cache cache) {

return cache.getTimeOut()*1000 > Calendar.getInstance().getTimeInMillis();

}

}Cache类

public class Cache {

private String key;//缓存ID

private Object value;//缓存数据

private long timeOut;//更新时间

public Cache() {

super();

}

public Cache(String key, Object value, long timeOut) {

this.key = key;

this.value = value;

this.timeOut = timeOut;

}

public String getKey() {

return key;

}

public void setKey(String key) {

this.key = key;

}

public Object getValue() {

return value;

}

public void setValue(Object value) {

this.value = value;

}

public long getTimeOut() {

return timeOut;

}

public void setTimeOut(long timeOut) {

this.timeOut = timeOut;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值