java自定义缓存_JAVA 实现自定义的缓存实现

本文档展示了如何在JAVA中实现一个自定义的缓存系统。`CacheListHandler` 类提供了一个简单的并发映射缓存,使用 `SimpleConcurrentMap` 存储缓存实体,并通过 `TimeoutTimerThread` 定时线程来处理缓存过期。方法包括添加、获取、检查、删除缓存,以及清除全部缓存。过期检查机制确保了无效的缓存会被及时清理。
摘要由CSDN通过智能技术生成

package com.cttc.cache.handler;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

import com.cttc.cache.entity.CacheEntity;

import com.cttc.cache.entity.SimpleConcurrentMap;

public class CacheListHandler {

private static final long SECOND_TIME = 1000;

private static final SimpleConcurrentMap map;

private static final List tempList;

static{

tempList = new ArrayList();

map = new SimpleConcurrentMap(new HashMap(1<<18));

new Thread(new TimeoutTimerThread()).start();

}

/**

* 增加缓存对象

* @param key

* @param ce

*/

public static void addCache(String key, CacheEntity ce){

addCache(key, ce, ce.getValidityTime());

}

/**

* 增加缓存对象

* @param key

* @param ce

* @param validityTime 有效时间

*/

public static synchronized void addCache(String key, CacheEntity ce, int validityTime){

ce.setTimeoutStamp(System.currentTimeMillis() + validityTime * SECOND_TIME);

map.put(key, ce);

//添加到过期处理队列

tempList.add(ce);

}

/**

* 获取缓存对象

* @param key

* @return

*/

public static synchronized CacheEntity getCache(String key){

return map.get(key);

}

/**

* 检查是否含有制定key的缓冲

* @param key

* @return

*/

public static synchronized boolean isConcurrent(String key){

return map.containsKey(key);

}

/**

* 删除缓存

* @param key

*/

public static synchronized void removeCache(String key){

map.remove(key);

}

/**

* 获取缓存大小

* @param key

*/

public static int getCacheSize(){

return map.size();

}

/**

* 清除全部缓存

*/

public static synchronized void clearCache(){

tempList.clear();

map.clear();

System.out.println("clear cache");

}

static class TimeoutTimerThread implements Runnable {

public void run(){

while(true){

try {

checkTime();

} catch (Exception e) {

e.printStackTrace();

}

}

}

/**

* 过期缓存的具体处理方法

* @throws Exception

*/

private void checkTime() throws Exception{

//"开始处理过期 ";

CacheEntity tce = null;

long timoutTime = 1000L;

//" 过期队列大小 : "+tempList.size());

if(1 > tempList.size()){

System.out.println("过期队列空,开始轮询");

timoutTime = 1000L;

Thread.sleep(timoutTime);

return;

}

tce = tempList.get(0);

timoutTime = tce.getTimeoutStamp() - System.currentTimeMillis();

//" 过期时间 : "+timoutTime);

if(0 

//设定过期时间

Thread.sleep(timoutTime);

return;

}

System.out.print(" 清除过期缓存 : "+tce.getCacheKey());

//清除过期缓存和删除对应的缓存队列

tempList.remove(tce);

removeCache(tce.getCacheKey());

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值