English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Implementation of Common Cache Mechanism in Java

CacheThat is, keeping the objects frequently called by the program or system in memory, so that they can be quickly accessed during use without having to create new duplicate instances. This can reduce system overhead and improve system efficiency.

Caching can mainly be divided into two categories:   

Firstly, file cache, as the name implies, file cache refers to storing data on disk, regardless of whether it is in XML format, serialized file DAT format, or other file formats; 

Secondly, memory cache, which is to implement a static Map in a class and perform routine addition, deletion, and query operations on this Map.

import java.util.*; 
 //Description: Cache management 
 //The expandable function: When the cache reaches memory overflow, it is necessary to clear the earliest cache objects, which requires saving the creation time for each cache object 
public class CacheManager { 
 private static HashMap cacheMap = new HashMap(); 
 //Single instance constructor method 
 private CacheManager() { 
  super(); 
 } 
 //Get boolean value cache 
 public static boolean getSimpleFlag(String key){ 
  try{ 
   return (Boolean) cacheMap.get(key); 
  } 
   return false; 
  } 
 } 
 public static long getServerStartdt(String key){ 
  try { 
   return (Long)cacheMap.get(key); 
  } 
   return 0; 
  } 
 } 
 //Set boolean value cache 
 public synchronized static boolean setSimpleFlag(String key, boolean flag){ 
  if (flag && getSimpleFlag(key)) {//If true, it is not allowed to be overwritten 
   return false; 
  } else { 
   cacheMap.put(key, flag); 
   return true; 
  } 
 } 
 public synchronized static boolean setSimpleFlag(String key, long serverbegrundt){ 
  if (cacheMap.get(key) == null) { 
   cacheMap.put(key, serverbegrundt); 
   return true; 
  } else { 
   return false; 
  } 
 } 
 //Get the cache. Synchronized static method 
 private synchronized static Cache getCache(String key) { 
  return (Cache) cacheMap.get(key); 
 } 
 //Determine if there is a cache existing 
 private synchronized static boolean hasCache(String key) { 
  return cacheMap.containsKey(key); 
 } 
 //Clear all caches 
 public synchronized static void clearAll() { 
  cacheMap.clear(); 
 } 
 //Clear a specific type of cache by traversing all objects under HASHMAP to determine if its KEY matches the entered TYPE 
 public synchronized static void clearAll(String type) { 
  Iterator i = cacheMap.entrySet().iterator(); 
  String key; 
  ArrayList arr = new ArrayList() 
  try { 
   while (i.hasNext()) { 
    java.util.Map.Entry entry = (java.util.Map.Entry) i.next(); 
    key = (String) entry.getKey(); 
    if (key.startsWith(type)) { //Delete if it matches 
     arr.add(key); 
    } 
   } 
   for (int k = 0; k < arr.size(); k++) { 
    clearOnly(arr.get(k)); 
   } 
  } 
   ex.printStackTrace(); 
  } 
 } 
 //Clear the specified cache 
 public synchronized static void clearOnly(String key) { 
  cacheMap.remove(key); 
 } 
 //Load cache 
 public synchronized static void putCache(String key, Cache obj) { 
  cacheMap.put(key, obj); 
 } 
 //Get cache information 
 public static Cache getCacheInfo(String key) { 
  if (hasCache(key)) { 
   Cache cache = getCache(key); 
   if (cacheExpired(cache)) { //Call the method to judge whether to terminate 
    cache.setExpired(true); 
   } 
   return cache; 
  }else 
   return null; 
 } 
 //Load cache information 
 public static void putCacheInfo(String key, Cache obj, long dt, boolean expired) { 
  Cache cache = new Cache(); 
  cache.setKey(key); 
  cache.setTimeOut(dt + System.currentTimeMillis()); //Set the cache update time after how long 
  cache.setValue(obj); 
  cache.setExpired(expired); //The default termination status when loading cache is FALSE 
  cacheMap.put(key, cache); 
 } 
 //Rewrite the method for loading cache information 
 public static void putCacheInfo(String key, Cache obj, long dt){ 
  Cache cache = new Cache(); 
  cache.setKey(key); 
  cache.setTimeOut(dt+System.currentTimeMillis()); 
  cache.setValue(obj); 
  cache.setExpired(false); 
  cacheMap.put(key, cache); 
 } 
 //Determine if the cache has been terminated 
 public static boolean cacheExpired(Cache cache) { 
  if (null == cache) { //The cache to be passed in does not exist 
   return false; 
  } 
  long nowDt = System.currentTimeMillis(); //The current milliseconds of the system 
  long cacheDt = cache.getTimeOut(); //The expiration milliseconds in the cache 
  if (cacheDt <= 0||cacheDt>nowDt) { //If the expiration time is less than or equal to zero, or if the expiration time is greater than the current time, then it is FALSE 
   return false; 
  } //Exceeds the expiration time, meaning it has expired 
   return true; 
  } 
 } 
 //Get the size in the cache 
 public static int getCacheSize() { 
  return cacheMap.size(); 
 } 
 //Get the size of the specified type 
 public static int getCacheSize(String type) { 
  int k = 0; 
  Iterator i = cacheMap.entrySet().iterator(); 
  String key; 
  try { 
   while (i.hasNext()) { 
    java.util.Map.Entry entry = (java.util.Map.Entry) i.next(); 
    key = (String) entry.getKey(); 
    if (key.indexOf(type) != -1) { //Delete if it matches 
     k++; 
    } 
   } 
  } 
   ex.printStackTrace(); 
  } 
  return k; 
 } 
 //Get all key names in the cache object 
 public static ArrayList getCacheAllkey() { 
  ArrayList a = new ArrayList(); 
  try { 
   Iterator i = cacheMap.entrySet().iterator(); 
   while (i.hasNext()) { 
    java.util.Map.Entry entry = (java.util.Map.Entry) i.next(); 
    a.add((String) entry.getKey()); 
   } 
  } 
   return a; 
  } 
 } 
 //Get the key name of the specified type in the cache object 
 public static ArrayList getCacheListkey(String type) { 
  ArrayList a = new ArrayList(); 
  String key; 
  try { 
   Iterator i = cacheMap.entrySet().iterator(); 
   while (i.hasNext()) { 
    java.util.Map.Entry entry = (java.util.Map.Entry) i.next(); 
    key = (String) entry.getKey(); 
    if (key.indexOf(type) != -1) { 
     a.add(key); 
    } 
   } 
  } 
   return a; 
  } 
 } 
} 
package lhm.hcy.guge.frameset.cache; 
public class Cache { 
  private String key;//Cache ID 
  private Object value;//Cached data 
  private long timeOut;//Update time 
  private boolean expired; //Whether to terminate 
  public Cache() { 
    super(); 
  } 
  public Cache(String key, Object value, long timeOut, boolean expired) { 
    this.key = key; 
    this.value = value; 
    this.timeOut = timeOut; 
    this.expired = expired; 
  } 
  public String getKey() { 
    return key; 
  } 
  public long getTimeOut() { 
    return timeOut; 
  } 
  public Object getValue() { 
    return value; 
  } 
  public void setKey(String string) { 
    key = string; 
  } 
  public void setTimeOut(long l) { 
    timeOut = l; 
  } 
  public void setValue(Object object) { 
    value = object; 
  } 
  public boolean isExpired() { 
    return expired; 
  } 
  public void setExpired(boolean b) { 
    expired = b; 
  } 
} 
//Test class, 
class Test { 
 public static void main(String[] args) { 
  System.out.println(CacheManager.getSimpleFlag("alksd")); 
//  CacheManager.putCache("abc", new Cache()); 
//  CacheManager.putCache("def", new Cache()); 
//  CacheManager.putCache("ccc", new Cache()); 
//  CacheManager.clearOnly(""); 
//  Cache c = new Cache(); 
//  for (int i = 0; i < 10; i++) { 
//   CacheManager.putCache(""); + i, c); 
//  } 
//  CacheManager.putCache("aaaaaaaa", c); 
//  CacheManager.putCache("abchcy;alskd", c); 
//  CacheManager.putCache("cccccccc", c); 
//  CacheManager.putCache("abcoqiwhcy", c); 
//  System.out.println("The size before deletion:");+CacheManager.getCacheSize()); 
//  CacheManager.getCacheAllkey(); 
//  CacheManager.clearAll("aaaa"); 
//  System.out.println("The size after deletion:");+CacheManager.getCacheSize()); 
//  CacheManager.getCacheAllkey(); 
 } 
}

That's all for this article. I hope it will be helpful to everyone's learning and I hope everyone will support the Yelling Tutorial more.

Declaration: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to notice#w3Please report any infringement by email to codebox.com (replace # with @) and provide relevant evidence. Once verified, this site will immediately delete the infringing content.

You May Also Like