Simple Example of LRU Algorithm

Source: Internet
Author: User
Tags set set

Package com. aspboy. Base. cache;

/*
* Created on 2004-
*
* The "least recently used algorithm" (LRU algorithm) removes the rows that have been least accessed in the recent period.
* Therefore, you must set a counter for each row. The LRU algorithm clears the counters of hit rows and Adds 1 to the counters of other rows.
* If a replacement is required, the data row with the highest counter count is eliminated.
* This is an efficient and scientific algorithm. In the counter clearing process, you can remove unnecessary data from the cache after frequent calls,
* Improves the cache utilization.
*/

Import java. util. hashmap;
Import java. util. iterator;
Import java. util. Set;

/**
* @ Author Liu Yueqing
*
* Recently, the minimum algorithm window-preferences-Java-code style-code templates is used.
*/
Public class LRU
{
Protected hashmap lrucache = new hashmap (2 );

// Maximum number of operable Use Times
Protected int MAX_INTEGER_NUMBER = 2147483647;

// Number of objects saved in the cache
Protected int max_object_num= 1000;

Public LRU ()
{
}

Public LRU (int maxObjectNum)
{
Max_object_num = maxObjectNum;
}

/**
* Add an object to the cache.
* @ Param key
* @ Param value
*/
Public Object put (Object key, Object value)
{
CacheObject newValue = new CacheObject (value );
If (lruCache. size ()> = max_object_num)
{
Removel.pdf ();
}

Return lruCache. put (key, newValue );
}

/**
* Use the key to get the object
*
* @ Param key
* @ Return
*/
Public Object get (Object key)
{
CacheObject object = (CacheObject) lruCache. get (key );
If (object = null)
{
Return null;
}

// Based on the LRU algorithm principle, add the hit object calculator 0 and the calculation value of other objects to 1
Set set = lruCache. keySet ();
Iterator iter = set. iterator ();
Object keyObject = null;
CacheObject cacheObject = null;
While (iter. hasNext ())
{
Keyobject = ITER. Next ();
Cacheobject = (cacheobject) lrucache. Get (keyobject );
Cacheobject. setusetimes (cacheobject. getusetimes () + 1 );
}
Object. setusetimes (0 );

Return object! = NULL? Object. getvalue (): NULL;
}

Public Boolean containskey (Object key)
{
Return lrucache. containskey (key );
}

Public void clear ()
{
LruCache. clear ();
}

Public int size ()
{
Return lruCache. size ();
}

Public boolean isEmpty ()
{
Return lruCache. isEmpty ();
}

Public boolean containsValue (Object value)
{
Return lruCache. containsKey (value );
}

/**
* Remove objects that use the least amount of data
*/
Public void removel.pdf ()
{
Object leaseuseobjectkey = NULL;
Int usetimes = 0;

Set set = lrucache. keyset ();
Iterator iter = set. iterator ();
While (ITER. hasnext ())
{
Object keyobject = ITER. Next ();
Cacheobject object = (cacheobject) lrucache. Get (keyobject );
If (object. getusetimes ()> usetimes)
{
Usetimes = object. getusetimes ();
Leaseuseobjectkey = keyobject;
}
}
Lrucache. Remove (leaseuseobjectkey );
}

Public set keyset ()
{
Return lrucache. keyset ();
}
/**
* Remove objects that are most frequently used
*/
Public void removeMost ()
{
Object leaseUseObjectKey = null;
Int usetimes = MAX_INTEGER_NUMBER;

Set set = lruCache. keySet ();
Iterator iter = set. iterator ();
While (iter. hasNext ())
{
Object keyObject = iter. next ();
CacheObject object = (CacheObject) lruCache. get (keyObject );
If (object. getUsetimes () <usetimes)
{
Usetimes = object. getUsetimes ();
LeaseUseObjectKey = keyObject;
}
}
LruCache. remove (leaseUseObjectKey );
}

/**
* Remove the first cached object
*/
Public void removeEarly ()
{
Object leaseUseObjectKey = null;
Long time = System. currentTimeMillis () + 365*24*60*60*1000;

Set set = lruCache. keySet ();
Iterator iter = set. iterator ();
While (iter. hasNext ())
{
Object keyObject = iter. next ();
CacheObject object = (CacheObject) lruCache. get (keyObject );
If (object. getPushtime () <time)
{
Time = object. getPushtime ();
LeaseUseObjectKey = keyObject;
}
}
LruCache. remove (leaseUseObjectKey );
}

/**
* Remove the latest object.
*/
Public void removeLater ()
{
Object leaseUseObjectKey = null;
Long time =-1;

Set set = lruCache. keySet ();
Iterator iter = set. iterator ();
While (iter. hasNext ())
{
Object keyObject = iter. next ();
CacheObject object = (CacheObject) lruCache. get (keyObject );
If (object. getPushtime ()> time)
{
Time = object. getPushtime ();
LeaseUseObjectKey = keyObject;
}
}
LruCache. remove (leaseUseObjectKey );
}

/**
* Delete A key value and corresponding object
* @ Param key
*/
Public void remove (Object key)
{
LruCache. remove (key );
}

Public static void main (String [] args)
{
LRU lru = new LRU (4 );
Lru. put ("a", "The A String ");
Lru. put ("B", "The B String ");
Lru. put ("d", "The D String ");
Lru. put ("c", "The C String ");

System. out. println (lru. toString ());

LRU. Get ("");
LRU. Get ("B ");
LRU. Get ("D ");
LRU. Get ("");
LRU. Get ("B ");
LRU. Get ("D ");
LRU. Put ("e", "The E string ");
LRU. Get ("e ");
LRU. Get ("e ");
LRU. Get ("e ");
LRU. Get ("e ");
System. Out. println (LRU. tostring ());
}

Public String toString ()
{
StringBuffer strBf = new StringBuffer (10 );
Set set1 = lruCache. keySet ();
Iterator iter1 = set1.iterator ();
While (iter1.hasNext ())
{
Object key = iter1.next ();
StrBf. append (key + "= ");
StrBf. append (lruCache. get (key ));
StrBf. append ("/n ");
}
Return strBf. toString ();
}


}

 

 

Package com. aspboy. base. cache;

/*
* Created on 2004-9-7
*
* TODO To change the template for this generated file go
* Window-Preferences-Java-Code Style-Code Templates
*/
/**

*
* TODO To change the template for this generated type comment go
* Window-Preferences-Java-Code Style-Code Templates
*/
Public class CacheObject
{
Long pushtime = 0;

Int usetimes = 0;

Object value = NULL;

Cacheobject (object value)
{
Pushtime = system. currenttimemillis ();
Usetimes = 0;
This. value = value;
}

/**
* @ Return returns the pushtime.
*/
Public final long getpushtime ()
{
Return pushtime;
}

/**
* @ Return returns the usetimes.
*/
Public final int getusetimes ()
{
Return usetimes;
}
/**
* @ Param usetimes the usetimes to set.
*/
Public final void setusetimes (INT usetimes)
{
This. usetimes = usetimes;
}
/**
* @ Return returns the value.
*/
Public final object getvalue ()
{
Return value;
}
/**
* @ Param value the value to set.
*/
Public final void setvalue (object value)
{
This. value = value;
}

Public String tostring ()
{
Stringbuffer strbf = new stringbuffer (10 );
Strbf. append ("value =" + value + '/N ');
StrBf. append ("pushtime =" + pushtime + '/N ');
StrBf. append ("usetimes =" + usetimes + '/N ');
Return strBf. toString ();
}
}

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.