Java in-process cache

Source: Internet
Author: User

Today I talked to my colleagues about caching and implementing the process cache in Java. The main idea here is to do a cache with a map. The cache has a lifetime, and it deletes the cache when it expires. There are two removal strategies to consider here, one for a thread that periodically removes the expired key. The second is, the culling mode, lazy, access to a key when only to check whether the key expires, expired deleted.

First, the value to be cached is encapsulated in a layer, with a timestamp

/*** Created by GXF on 2017/6/28.*/ Public classValuewithtimestamp<v>{    Private LongExpiretime; PrivateV value;  PublicValuewithtimestamp (Longexpiretime, V value) {         This. Expiretime =Expiretime;  This. Value =value; }     Public LongGetexpiretime () {returnExpiretime; }     Public voidSetexpiretime (Longexpiretime) {         This. Expiretime =Expiretime; }     PublicV GetValue () {returnvalue; }     Public voidSetValue (V value) { This. Value =value; }}

OK, the thread periodically deletes the policy mode

ImportJava.util.Map;ImportJava.util.concurrent.ConcurrentHashMap;/*** Created by GXF on 2017/6/28. * Use threads to periodically delete expired keys*/ Public classCachemap<k, v>  {    //here to use Concurrenthashmap to avoid, clean, the main thread to modify the Chache, causing the exception,//use Concurrenthashmap to control concurrent modifications to the cache    PrivateMap<k, valuewithtimestamp<v>> cache =NewConcurrenthashmap<k, valuewithtimestamp<v>>(); Private Static BooleanCleantaskisrunning =false; //TTL Expiration Time unit: Seconds     Public voidPut (K key, V value,intTTL) {        LongExpiretime = System.currenttimemillis () + TTL * 1000; Valuewithtimestamp<V> Valuewithtimestamp =NewValuewithtimestamp<>(expiretime, value);        Cache.put (key, Valuewithtimestamp); if(!cleantaskisrunning)            {Startcleantask (); Cleantaskisrunning= !cleantaskisrunning; }    }     PublicV get (K key) {Valuewithtimestamp<V> Valuewithtimestamp =Cache.get (key); return NULL= = Valuewithtimestamp?NULL: Valuewithtimestamp.getvalue (); }    /*** Start cleanup thread **/    Private voidStartcleantask () {Thread Cleanthread=NewThread (NewCleantask ());    Cleanthread.start (); }    /*** Cleanup of expired key **/    classCleantaskImplementsrunnable{ Public voidrun () { while(true){                LongCurrentTime =System.currenttimemillis (); //Traverse Map                 for(Map.entry<k, valuewithtimestamp<v>>Entry:cache.entrySet ()) {Valuewithtimestamp<V> Valuewithtimestamp =Entry.getvalue (); LongExpiretime =Valuewithtimestamp.getexpiretime (); //It's time to expire.                    if(CurrentTime >expiretime) {System.out.println ("Key:" + entry.getkey () + "expired");                    Cache.remove (Entry.getkey ()); } //if}// for//Scan the map object every 1s                Try{Thread.Sleep (1000); } Catch(interruptedexception e) {e.printstacktrace (); }            } // while        }    }}

Note that you need to use Concurrenthashmap to do the caching. Otherwise, there will be a multiline thread operation exception to the map object

Second strategy, culling mode

ImportJava.util.Map;ImportJava.util.concurrent.ConcurrentHashMap;/*** Created by (+) on 2017/6/28. * Use lazy mode to get the key when the expired key is removed*/ Public classCachemap1<k, v> {    PrivateMap<k, valuewithtimestamp<v>> cache =NewConcurrenthashmap<k, valuewithtimestamp<v>>();  Public voidPut (K key, V value,intTTL) {        LongExpiretime = System.currenttimemillis () + TTL * 1000; Valuewithtimestamp<V> Valuewithtimestamp =NewValuewithtimestamp<v>(expiretime, value);    Cache.put (key, Valuewithtimestamp); }     PublicV get (K key) {Valuewithtimestamp<V> Valuewithtimestamp =Cache.get (key); LongExpiretime =Valuewithtimestamp.getexpiretime (); LongCurrentTime =System.currenttimemillis (); //Key has expired, deleted, returned null        if(CurrentTime >expiretime) {System.out.println ("Key:" + key + "is expired.");            Cache.remove (key); return NULL; }        returnCache.get (key). GetValue (); }}

Redis is used in the project and should be faster in this way, optimizing the code for two days

Java in-process cache

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.