熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java核心技術 >> 正文

Java實現簡單的緩存機制原理

2022-06-13   來源: 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();

  }

  }

  }

  }

  }


From:http://tw.wingwit.com/Article/program/Java/hx/201311/25737.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.