The implementation of the Cache caching mechanism is commonly used in Java

  • 2020-05-12 02:35:47
  • OfStack

Cache, is the program or system often to call the object stored in memory, 1 time its use can be quickly called, do not have to create new duplicate instances. Doing so can reduce overhead and improve system efficiency.

Caching can be divided into two main categories:

1. File caching, as the name implies, means storing data on disk, whether you do it in XML, DAT, or other file formats;

2. Memory cache, that is, the static Map in a class is implemented, and the Map is routinely added and deleted.


import java.util.*; 

 //Description:  Manage the cache  

 // Extensible features: when chche The earliest ones must be cleared when memory runs out 1 Cache objects, which requires the creation time to be saved for each cache object  

public class CacheManager { 
 private static HashMap cacheMap = new HashMap(); 

 // Single instance constructor  
 private CacheManager() { 
  super(); 
 } 
 // Gets the cache of Boolean values  
 public static boolean getSimpleFlag(String key){ 
  try{ 
   return (Boolean) cacheMap.get(key); 
  }catch(NullPointerException e){ 
   return false; 
  } 
 } 
 public static long getServerStartdt(String key){ 
  try { 
   return (Long)cacheMap.get(key); 
  } catch (Exception ex) { 
   return 0; 
  } 
 } 
 // Set the cache of Boolean values  
 public synchronized static boolean setSimpleFlag(String key,boolean flag){ 
  if (flag && getSimpleFlag(key)) {// If true 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; 
  } 
 } 


 // I get the cache. Synchronous static method  
 private synchronized static Cache getCache(String key) { 
  return (Cache) cacheMap.get(key); 
 } 

 // To determine if there is 1 A cache  
 private synchronized static boolean hasCache(String key) { 
  return cacheMap.containsKey(key); 
 } 

 // Clear all caches  
 public synchronized static void clearAll() { 
  cacheMap.clear(); 
 } 

 // Remove a 1 Classspecific cache , By iterating through HASHMAP Under all objects to determine its KEY With the incoming TYPE match  
 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)) { // If it matches, delete it  
     arr.add(key); 
    } 
   } 
   for (int k = 0; k < arr.size(); k++) { 
    clearOnly(arr.get(k)); 
   } 
  } catch (Exception ex) { 
   ex.printStackTrace(); 
  } 
 } 

 // Clears the specified cache  
 public synchronized static void clearOnly(String key) { 
  cacheMap.remove(key); 
 } 

 // Load the 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)) { // The call determines whether to terminate the method  
    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 how long to update the cache  
  cache.setValue(obj); 
  cache.setExpired(expired); // When the cache is loaded by default, the termination state is FALSE 
  cacheMap.put(key, cache); 
 } 
 // Override the load cache information method  
 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); 
 } 

 // Determines whether the cache is terminated  
 public static boolean cacheExpired(Cache cache) { 
  if (null == cache) { // The incoming cache does not exist  
   return false; 
  } 
  long nowDt = System.currentTimeMillis(); // The number of milliseconds currently in the system  
  long cacheDt = cache.getTimeOut(); // The number of expired milliseconds in the cache  
  if (cacheDt <= 0||cacheDt>nowDt) { // When the expiration time is less than or equal to zero , Or when the expiration time is greater than the current time FALSE 
   return false; 
  } else { // Greater than expiration time   The overdue  
   return true; 
  } 
 } 

 // Gets the size in the cache  
 public static int getCacheSize() { 
  return cacheMap.size(); 
 } 

 // Gets 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) { // If it matches, delete it  
     k++; 
    } 
   } 
  } catch (Exception ex) { 
   ex.printStackTrace(); 
  } 

  return k; 
 } 

 // Gets all key value 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()); 
   } 
  } catch (Exception ex) {} finally { 
   return a; 
  } 
 } 

 // Gets the specified type in the cache object   Is the name of the key value  
 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); 
    } 
   } 
  } catch (Exception ex) {} finally { 
   return a; 
  } 
 } 

} 


package lhm.hcy.guge.frameset.cache; 

public class Cache { 
  private String key;// The cache ID 
  private Object value;// Cache 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; 
  } 
} 

// The 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(" Size before deletion: "+CacheManager.getCacheSize()); 
//  CacheManager.getCacheAllkey(); 
//  CacheManager.clearAll("aaaa"); 
//  System.out.println(" Size after deletion: "+CacheManager.getCacheSize()); 
//  CacheManager.getCacheAllkey(); 


 } 
}

Related articles: