The principle is to use LinkedHashMap. When the cache size exceeds the upper limit, the oldest tuples will be deleted.
The implementation code is as follows:
Copy codeThe Code is as follows: import java. util. LinkedHashMap;
Import java. util. Map;
Public class LRUCache {
Public static class CachedData {
Private Object data = null;
Private long time = 0;
Private boolean refreshing = false;
Public CachedData (Object data ){
This. data = data;
This. time = System. currentTimeMillis ();
}
Public Object getData (){
Return data;
}
Public long getTime (){
Return time;
}
Public void setTime (long time ){
This. time = time;
}
Public boolean getRefreshing (){
Return refreshing;
}
Public void setRefreshing (boolean B ){
This. refreshing = B;
}
}
Protected static class CacheMap extends hashmap {
Protected int maxsize = 0;
Public CacheMap (int maxsize ){
Super (maxsize * 4/3 + 1, 0.75f, true );
This. maxsize = maxsize;
}
Protected boolean removeEldestEntry (Map. Entry eldest ){
Return size ()> this. maxsize;
}
}
Protected CacheMap map = null;
Public LRUCache (int size ){
This. map = new CacheMap (size );
}
Public synchronized void set (Object key, Object value ){
Map. remove (key );
Map. put (key, new CachedData (value ));
}
Public synchronized void remove (Object key ){
Map. remove (key );
}
Public synchronized CachedData get (Object key ){
CachedData value = (CachedData) map. get (key );
If (value = null ){
Return null;
}
Map. remove (key );
Map. put (key, value );
Return value;
}
Public int usage (){
Return map. size ();
}
Public int capacity (){
Return map. maxsize;
}
Public void clear (){
Map. clear ();
}
}