Build level two cache with Linkedhashmap's LRU feature and SoftReference soft reference

Source: Internet
Author: User

Lru:least recently Used (least recently used algorithm). The Linkedhashmap constructor can specify its iteration order: LinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder)  set Accessorder to True, then iterate in the order of access. When Linkedhashmap calls put or Putall successfully inserts a key value, the Removeeldestentry method is called, depending on the return value of the method to determine whether to delete the oldest object (Accessorder is true after iterating according to the Order of access). To ensure that the map size does not exceed a certain value, you can override the Removeeldestentry method to return True to delete the oldest object.

SoftReference soft references, such as New softreference<object> (new Object), to preserve a soft reference to an Object, in the upcoming oom, The GC reclaims the objects referenced by the softreference. So, when the memory is sufficient, its get () method returns the object it refers to, and the Get method returns null after the Oom is about to cause the GC to be recycled.

Firstcache.java:

 Public classFirstcache<k,v>extendsLinkedhashmap<k,v>{    Private Static Final LongSerialversionuid = 1L; Private intmax_size = 100; PrivateSecondcache<k, v> Secondcache =NewSecondcache<k, v>();  PublicFirstcache () {Super(); }     PublicFirstcache (intmax_size) {        //using the Accessorder property of the Linkedhashmap construction method to construct the LRU cache//Accessorder is true, sort by access order and when Accessorder is false, sort by insert order        Super(100,0.75f,true);  This. Max_size =max_size; }    //When map calls the put or Putall method to insert a entry successfully, the bool value returned by Removeeldestentry determines whether to delete the data corresponding to the least recently used//returns True to delete returns false reserved@Overrideprotected BooleanRemoveeldestentry (entry<k,v>entry) {        if(Size () >=max_size) {            //Use the SoftReference feature to do level two cache, SoftReference (soft reference) only when the GC will be retrieved when the oom is about to beSecondcache.put (Entry.getkey (), Entry.getvalue ()); System.out.println ("Level two cache capacity" +secondcache.notemptysize ()); return true; }        return false; }}

Secondcache.java:

 Public classSecondcache<k,v>{Map<K,SoftReference<V>> Secondcachemap =NewHashmap<k, softreference<v>>();  Public voidput (K k,v V) {softreference<Object> o =NewSoftreference<object> (NewObject ()); Secondcachemap.put (k,NewSoftreference<v>(v)); }        /*** Delete value null key value pair, return the number of value not NULL in whole map*/     Public intnotemptysize () {intCount = 0; Iterator<entry<k, softreference<v>>> iter =Secondcachemap.entryset (). iterator ();  while(Iter.hasnext ()) {if(Iter.next (). GetValue (). get () = =NULL) Iter.remove (); ElseCount++; }        returncount; }}

Test method: Set the virtual machine parameter to-xms64m-xmx64m:

 Public classLRUCache { Public Static Final intMax_size = 20;  Public Static intCount = 0;  Public Static voidMain (string[] args) {//First- level cache, using Linkedhashmap's LRU featuresFirstcache<integer, student> Firstcache =NewFirstcache<integer, Student> (20);//Hashmap<integer, student> m = new Hashmap<integer, student> ();         while(true) {Count++; Student s=NewStudent (); //If you use HashMap to store it, you throw an oom when Count is about 59 .//M.put (count, s);//System.out.println (count);Firstcache.put (count, s); if(Count >max_size)            {System.out.println (Firstcache.size ()); }        }    }}

Build level two cache with Linkedhashmap's LRU feature and SoftReference soft reference

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.