"Java/android Performance Excellent 4" Preloaddatacache support prefetch data cache, easy to use, support a variety of cache algorithms, support different network types, strong extensibility

Source: Internet
Author: User
Tags prefetch

This article transferred from: http://www.trinea.cn/android/preloaddatacache/

This article focuses on the use and functionality of a cache that supports automatic forward or backward access to new data . Android image memory cache visible Imagecache.

Main Features: (1). Easy to use (2). New data can be automatically pre-fetched (3). You can choose from a variety of cache algorithms (including FIFO, LIFO, LRU, MRU, LFU, MFU, etc.) or a custom cache algorithm (4). Good flow performance (with only one thread fetching data) (5). supports different types of network processing (6) The cache can be serialized to a local cache that can be recovered from a file (7). Strong extensibility (8). Most interfaces that contain maps

Application: Java and Android development in the acquisition of data more time-consuming applications, such as network communication, response slow data acquisition, in similar netease news, petals Such applications can play a very good effect. For the picture cache, you can use Imagecache directly.

1. Use

Introduce [email protected](Welcome star and Fork ^_^) as your project's library (how to pull the replacement code and add a public library), or you can extract the [email protected] part of it.

Test scenario: Get each data takes 2 seconds, 10 times to get the scene effect comparison, cache time (ms): 20004, cache after (ms): 4026. The cache hit rate is 80%. The instance code is as follows:

Private Staticstring[] data = {"Data1", "Data2", "Data3", "data4", "Data5", "Data6", "Data7",        "Data8", "data9", "data10", "Data11", "Data12", "Data13", "Data14", "Data15", "Data16", "Data17", "Data18",        "Data19", "DATA20"                   };Private StaticArraylist<string> keylist =NewArraylist<string>();Private Staticmap<string, string> DataSource =NewHashmap<string, string>();Private Static intindex = 0; /*** Initialize data source*/Static {     for(inti = 0; i < data.length; i++) {String temp=integer.tostring (i);        Datasource.put (temp, data[i]);    Keylist.add (temp); }} /*** Simulate getting data from a data source * *@return*/ Public StaticString Getslowresponsedata () {Try{Thread.Sleep (2000); } Catch(interruptedexception e) {e.printstacktrace (); }    returnDatasource.get (Integer.tostring ((index++)%keylist.size ()));}  Public Static voidMain (string[] args) {//init cache, Setongetdatalistenerpreloaddatacache<string, string> cache =NewPreloaddatacache<string, String> (5); Cache.setongetdatalistener ((NewOngetdatalistener<string, string>() {         Private Static Final LongSerialversionuid = 1L; @Override PublicCacheobject<string>Ongetdata (String key) {CacheObject<String> o =NewCacheobject<string>();            O.setdata (Getslowresponsedata ()); returno;    }    })); Cache.setcachefullremovetype (NewRemovetypeentertimefirst<string>()); //get data by Cache    intCount = 10; LongStart =System.currenttimemillis ();  for(inti = 0; I < count; i++) {System.out.print (Cache.get (integer.tostring (i), keylist). GetData ()+ " "); } System.out.println ("\ r \ n Cache elapsed Time (ms):" + (System.currenttimemillis ()-start) + ". Cache Hit Rate is "+cache.gethitrate ()+ "(" + cache.gethitcount () + "/" + (Cache.gethitcount () + Cache.getmisscount ()) + ")"); //Get Data NormalStart =System.currenttimemillis ();  for(inti = 0; I < count; i++) {System.out.print (Getslowresponsedata ()+ " "); } System.out.println ("\ r \ n Cache pre-time (ms):" + (System.currenttimemillis ()-start));}

As you can see from the Cache definition section of the above code, you only need to define Preloaddatacache and set the interface Setongetdatalistener to get the data, and then get the data using get.

2. Function Introduction
(1) Initializing the cache
You can initialize the cache in one of the following four ways
Preloaddatacache ()
Preloaddatacache (int)
Preloaddatacache (int, int)
Loadcache (String) recovering the cache from a file
Support cache size and get data thread pool size settings, default cache size is simplecache#default_max_size, the default thread pool size is based on the number of system CPUs.

(2), set the data acquisition method
public void Setongetdatalistener (ongetdatalistener<k, v> Ongetdatalistener)
Sets the way data gets. The cache obtains data and prefetch data through the interface.

(3) Obtaining and prefetching data
Public cacheobject<v> get (K key, list<k> keylist) gets a key (synchronous) and automatically caches new data in the order of key in Keylist, either forward or backward
Public cacheobject<v> get (K key) get a key (synchronous), but does not automatically fetch new data for caching
public void Setforwardcachenumber (int forwardcachenumber) sets the number of forward prefetch data, which defaults to preloaddatacache#default_forward_cache_ Number

public void Setbackwardcachenumber (int backwardcachenumber) sets default to the number of backward prefetch data, default is Preloaddatacache#default_backward_ Cache_number

(4), set cache algorithm
public void Setcachefullremovetype (cachefullremovetype<v> cachefullremovetype)
Sets the cache algorithm, which is the rule for deleting old data in order to insert new data when the cache is full.

Currently includes FIFO, LIFO, LRU, MRU, LFU, MFU, priority low first Delete, priority high first delete, data small first delete, data big first Delete, picture small first delete, picture big First Delete, file small first delete, file big first delete, never delete. You can also customize the cache algorithm by implementing Cachefullremovetype: The default is Removetypeentertimefirst, which is FIFO. The following is a detailed introduction

Removetypeentertimefirst FIFO first out, first go first delete
Removetypeentertimelast LIFO LIFO, after entry first delete
Removetypelastusedtimefirst LRU (Least recently user), first use delete first
Removetypelastusedtimelast MRU (most recently used), recently used first delete
Removetypeusedcountsmall LFU (Least frequently used), first removed with low frequency
Removetypeusedcountbig MRU (most frequently used), first removed with high frequency
Removetypeprioritylow Priority Low First delete
Removetypepriorityhigh Priority Low First delete
Removetypedrawablesmall a small picture first delete
Removetypedrawablelarge The big picture first delete

Removetypefilesmall file is small delete first

Removetypefilelarge file Big Delete First
Removetypedatabig data is deleted first, depending on the CompareTo function of the cached data
Removetypedatasmall data is deleted first, depending on the CompareTo function of the cached data
Removetypenotremove is not deleted, no new data is allowed to be inserted when the cache is full

The custom caching algorithm only needs to implement the Cachefullremovetype compare method. A comparison of less than 0 indicates that the result is deleted first

 Public class Implements Cachefullremovetype<t> {     privatestaticfinallong Serialversionuid = 1L;     @Override    publicint compare (cacheobject<t> obj1, cacheobject<t>  OBJ2) {        return (obj2.getpriority () > Obj1.getpriority ())? 1: ((obj2.getpriority () = = Obj1.getpriority ())? 0:-1);}    }

(5), optimized data read
A. Setting the data read HTTP time-out
public void sethttpreadtimeout (int httpreadtimeout)
If httpreadtimeout less than 0 means no timeout set, default is not set, in milliseconds

B. Set no network no read
public void SetContext (context context)
Setting the context, network connection failure does not create a new thread to request data.

C. Support for processing of different network types
public void setallowednetworktypes (int allowednetworktypes)
Set the allowed network types, either Preloaddatacache#network_mobile, Preloaddatacache#network_wifi, or both. Both are allowed by default.
Note: This interface must be SetContext (context context) before it takes effect

(6), cache element validity time
public void Setvalidtime (long validtime)
Setting the cache element validity time, less than 0 means that it will not expire, at which point the element is replaced only by Cachefullremovetype when the cache is full
Determine if a key is out of date by protected Boolean isexpired (K key)

(7), Cache hit ratio
Gethitrate (), Gethitcount (), GetMissCount () indicate cache hit ratio, hit count, number of misses, respectively

(8) serialization
Serialization requires cached data types to support serializable, and for serialization refer to the understanding and summary of Java serializable

Recovering a cache from a file using Loadcache (String)
Savecache (String, Simplecache) Save cache to file

(9), other interfaces similar to map
public boolean ContainsKey (K key) cache contains the key
Public cacheobject<v> Remove (K key) removes a key from the cache
public void Clear () empty cache
Public set<k> KeySet () cache in key collection
Public set<map.entry<k, Cacheobject<v>>> EntrySet () cache in Key,value key-value pairs collection
Public collection<cacheobject<v>> values () in the collection of elements in the cache
Public cacheobject<v> put (K key, V value) to manually insert an element
Public cacheobject<v> put (K key, cacheobject<v> value) to manually insert an element
Public cacheobject<v> get (K key) to get a key
public int getsize () Gets the number of valid elements in the cache
public int getmaxsize () gets the maximum number of elements in the cache

(10) Get Set
The above set can be used to get the corresponding value by the corresponding get
How to get Data using Getongetdatalistener ()
Getforwardcachenumber () Gets the number of auto forward caches
Getbackcachenumber () Gets the number of auto-backward caches
Getmaxsize () Get cache maximum Capacity
Getvalidtime () Gets the effective time, measured in milliseconds
Getcachefullremovetype () gets the cache full when the element type is deleted

"Java/android Performance Excellent 4" Preloaddatacache support prefetch data cache, easy to use, support a variety of cache algorithms, support different network types, strong extensibility

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.