In-depth analysis of Cache based on Java

Source: Internet
Author: User

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 ();
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.