A very simple java cache management class

This really sucks. Dozens of lines of code implement Java's cache all using JDK's classes.
package com.test.cache;

import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks. ReentrantLock;

public final class SimpleCacheMy<K,V> {
private Lock lock = new ReentrantLock(); //The lock function is similar to synchronized, but it is more powerful and efficient than synchronized
private final int maxCapacity; //Maximum capacity
//Adopt The map structure stores data
private final Map<K,V> emap; //limit pool
private final Map<K,V> lmap; //cache pool

public SimpleCacheMy(int maxCapacity){
this.maxCapacity = maxCapacity; //Set the maximum capacity
/*
* ConcurrentHashMap This class is a thread-safe map, and its efficiency is higher than hashtable
* The implementation principle of this class is to cut into multiple small maps, and then synchronize where they need to be synchronized
* */
emap = new ConcurrentHashMap<K,V>(maxCapacity );
/*
* WeakHashMap uses a reference mechanism internally to change the object stored by itself
. If it is found that the object is no longer referenced, the class will clear the object, so that the cache can be implemented with this class without considering the issue of the clearing mechanism.
* */
lmap = new WeakHashMap<K,V>(maxCapacity);
}

public V get(K k){
V v = emap.get(k); //First take from the limit pool
if(v==null){ //Not fetched and then fetched from the buffer pool, because lmap is thread-unsafe, so it needs to be synchronized.
try{
lock.lock(); 
v = lmap.get(k); //fetch from the buffer pool
}catch(Exception e){

}finally{
lock.unlock(); //note that you must use lock for synchronization try catch block, release in finally
}
if(v!=null){
emap.put(k, v); //If found, put it into the limit pool from the buffer pool.
}
}

return v;
}

public void put(K k,V v){
if(emap.size()>=maxCapacity){ //If the limit pool is full at this time, put
try{
lock.lock in the buffer pool ();
lmap.putAll(emap);
}catch(Exception e){}finally{
lock.unlock();
}

emap.clear(); //clear limit pool
}
emap.put(k, v); // into the limit pool
}
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327040568&siteId=291194637