Java uses Map to cache a simple instance

Source: Internet
Author: User
Tags object object


Sometimes a batch of data needs to be cached and eliminated according to the least recently used rules. At this time, we should think of LRUMap.
LRUMap is a fixed-size Map. When its capacity reaches the maximum value, the corresponding elements are eliminated using the least recently used rules.

The code is as follows: Copy code
LRUMap cache = newLRUMap (5 );
 
Cache. put ("01", "news 1 ");
Cache. put ("02", "news 2 ");
Cache. put ("03", "news 3 ");
Cache. put ("04", "news 4 ");
Cache. put ("05", "news 5 ");
 
String news1 = (String) cache. get ("01 ");
String news2 = (String) cache. get ("02 ");
String news3 = (String) cache. get ("04 ");
String news4 = (String) cache. get ("03 ");
String news5 = (String) cache. get ("02 ");
String news6 = (String) cache. get ("05 ");
 
Cache. put ("06", "news 6 ");
 
Iterator it = cache. entrySet (). iterator ();
While (it. hasNext ()){
Map. Entry entry = (Map. Entry) it. next ();
System. out. println (entry. getValue ());
}

 

LazyMap: when you need to obtain a key value but find that the key value does not exist, the key value is automatically filled, so you should consider using LazyMap. LazyMap uses the decoration mode to decorate a Map, A Transformer is used to determine the filling rule (or Factory) when the key value does not exist ).
 

The code is as follows: Copy code

Transformer reverseString = newTransformer (){
PublicObject transform (Object object ){
String name = (String) object;
String reverse = StringUtils. reverse (name );
Returnreverse;
       }
};
 
Map names = newHashMap ();
Map lazynames = LazyMap. decorate (names, reverseString );
 
System. out. println (lazynames. get ("hello "));
System. out. println (lazynames. get ("thanks "));
System. out. println (lazynames. get ("not at all "));
 
Factory factory = newFactory (){
PublicObject create (){
Return "NB ";
       }
};
 
Map lazyname = LazyMap. decorate (names, factory );
 
System. out. println (lazyname. get ("woshishei "));
System. out. println (lazyname. get ("nishishei "));
System. out. println (lazyname. get ("not at all "));

 

Combined use of LRUMap and LazyMap:

The code is as follows: Copy code

Transformer reverseString = newTransformer (){
PublicObject transform (Object object ){
String name = (String) object;
String reverse = StringUtils. reverse (name );
Returnreverse;
       }
};
 
LRUMap lruMap = newLRUMap (5 );
Map lazyMap = LazyMap. decorate (lruMap, reverseString );
 
String name0 = (String) lazyMap. get ("test0 ");
String name1 = (String) lazyMap. get ("test0 ");
String name2 = (String) lazyMap. get ("test0 ");
String name3 = (String) lazyMap. get ("test2 ");
String name4 = (String) lazyMap. get ("test4 ");
String name5 = (String) lazyMap. get ("test5 ");
String name6 = (String) lazyMap. get ("test0 ");
String name7 = (String) lazyMap. get ("test6 ");
String name8 = (String) lazyMap. get ("test8 ");
String name9 = (String) lazyMap. get ("test5 ");
 
Iterator it = lazyMap. entrySet (). iterator ();
While (it. hasNext ()){
Map. Entry entry = (Map. Entry) it. next ();
System. out. println (entry. getValue ());
    }

 

Of course, you can do anything in Transformer, such as crawling data from a website and converting it into a corresponding object.
The following code queries the IP address from the IP address library of pchome. First, it defines an ArticleTransformer object. Data is queried from a URL and returned each time based on the input parameters.

The code is as follows: Copy code
Public class ArticleTransformer implements Transformer {
 
Protected final static int BUF_SIZE = 300;
 
Protected String queryURL;
Public String getQueryURL () {return queryURL ;}
Public void setQueryURL (String queryURL) {this. queryURL = queryURL ;}
 
Protected long timeOut;
Public long getTimeOut () {return timeOut ;}
/**
* @ Param timeOut unit: ms
*/
Public void setTimeOut (long timeOut) {this. timeOut = timeOut ;}
 
Public Object transform (Object obj ){
ArticleRetriever retriever = new ArticleRetriever (String) obj );
Try {
Thread thread = new Thread (retriever );
Thread. start ();
Thread. join (timeOut );
// Thread. sleep (3*1000 );
} Catch (InterruptedException e ){
System. out. println ("url request time out .");
        }
Return retriever. getResponse ();
    }
 
Public class ArticleRetriever implements Runnable {
Private String name;
Private String response;
 
Public ArticleRetriever (String name ){
This. name = name;
        }
 
Public String getResponse (){
Return this. response;
        }
 
Public void run (){
 
HttpURL url = null;
 
Try {
HttpClient client = new HttpClient ();
 
Url = new HttpURL (queryURL + name );
 
GetMethod getMethod = new GetMethod (url. toString ());
 
GetMethod. getParams (). setContentCharset ("UTF-8 ");
 
Client.exe cuteMethod (getMethod );
 
Response = getMethod. getResponseBodyAsString ();
} Catch (Exception e ){
System. out. println ("Error get Article" + url );
            }
 
        }
    }
 
}
<SPAN style = "DISPLAY: none"> </SPAN>

 

Then the following code calls

The code is as follows: Copy code

String queryURL = "http://whois.pconline.com.cn/ip.jsp? Ip = ";
ArticleTransformer transformer = new ArticleTransformer ();
Transformer. setQueryURL (queryURL );
Transformer. setTimeOut (500 );
 
Map lruMap = new LRUMap (3 );
ArticleMap = LazyMap. decorate (lruMap, transformer );
 
String ip1 = (String) articleMap. get ("127.0.0.1 ");
String ip2 = (String) articleMap. get ("121.0.29.241 ");
String ip3 = (String) articleMap. get ("10.25.145.123 ");
String ip4 = (String) articleMap. get ("10.121.20.35 ");
String ip5 = (String) articleMap. get ("121.230.145.60 ");
String ip6 = (String) articleMap. get ("27.186.214.221 ");
String ip7 = (String) articleMap. get ("127.0.0.1 ");
 
Try {
Writer writer = new FileWriter ("D: // hello.txt ");
 
Iterator it = articleMap. entrySet (). iterator ();
While (it. hasNext ()){
Map. Entry entry = (Map. Entry) it. next ();
System. out. println (entry. getValue ());
If (entry. getValue () = null ){
Writer. write ("nulln ");
} Else {
Writer. write (String) entry. getValue ());
            }
        }
If (writer! = Null) writer. close ();
} Catch (IOException e ){
System. out. println ("Error write file ");
    }

 

Finally, the following results are output:

Taizhou (Taixing) Telecom, Jiangsu province
Baoding Telecom, Hebei province
Internet reserved address

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.