java

位置:IT落伍者 >> java >> 浏览文章

Java实现简单的缓存机制原理


发布日期:2022年03月03日
 
Java实现简单的缓存机制原理

package comqinbohui;

/*

设计思想来自-回钦波(qq:)

*/

public class CacheConfModel implements javaioSerializable{

private long beginTime;

private boolean isForever = false;

private int durableTime;

public long getBeginTime() {

return beginTime;

}

public void setBeginTime(long beginTime) {

thisbeginTime = beginTime;

}

public boolean isForever() {

return isForever;

}

public void setForever(boolean isForever) {

thisisForever = isForever;

}

public int getDurableTime() {

return durableTime;

}

public void setDurableTime(int durableTime) {

thisdurableTime = durableTime;

}

}

package comqinbohui;

import javautil*;

import testCacheConfModel;

/*

设计思想来自-回钦波(qq:)

*/

public class CacheMgr {

private static Map cacheMap = new HashMap();

private static Map cacheConfMap = new HashMap();

private CacheMgr(){

}

private static CacheMgr cm = null;

public static CacheMgr getInstance(){

if(cm==null){

cm = new CacheMgr();

Thread t = new ClearCache();

tstart();

}

return cm;

}

/**

* 增加缓存

* @param key

* @param value

* @param ccm 缓存对象

* @return

*/

public boolean addCache(Object keyObject valueCacheConfModel ccm){

boolean flag = false;

cacheMapput(key value);

cacheConfMapput(key ccm);

Systemoutprintln(now addcache==+cacheMapsize());

return true;

}

/**

* 删除缓存

* @param key

* @return

*/

public boolean removeCache(Object key){

cacheMapremove(key);

cacheConfMapremove(key);

Systemoutprintln(now removeCache==+cacheMapsize());

return true;

}

/**

* 清除缓存的类

* @author wanglj

* 继承Thread线程类

*/

private static class ClearCache extends Thread{

public void run(){

while(true){

Set tempSet = new HashSet();

Set set = cacheConfMapkeySet();

Iterator it = erator();

while(ithasNext()){

Object key = itnext();

CacheConfModel ccm = (CacheConfModel)cacheConfMapget(key);

//比较是否需要清除

if(!ccmisForever()){

if((new Date()getTime()ccmgetBeginTime())>= ccmgetDurableTime()**){

//可以清除先记录下来

tempSetadd(key);

}

}

}

//真正清除

Iterator tempIt = erator();

while(tempIthasNext()){

Object key = tempItnext();

cacheMapremove(key);

cacheConfMapremove(key);

}

Systemoutprintln(now thread================>+cacheMapsize());

//休息

try {

Threadsleep(*L);

} catch (InterruptedException e) {

// TODO Autogenerated catch block

eprintStackTrace();

}

}

}

}

}

上一篇:用Java构造自己的媒体播放器

下一篇:面向Java开发人员的Scala指南: 构建计算器,第1 部分