Android lightweight cache framework ASimpleCache Analysis

Source: Internet
Author: User
Tags time in milliseconds

Android lightweight cache framework ASimpleCache Analysis

 

Official introduction:

ASimpleCache is a lightweight open-source cache framework developed for android. Lightweight to only one java file (simplified from a dozen classes ).

(There is a problem that the author said that automatic invalidation is actually to determine whether the data stored in the cache has expired when obtaining data. If it expires, the data cache is deleted and null is returned. Of course, if automatic deletion is true, you can only enable the Service and constantly determine whether the deletion is expired. It is not necessary)


--------------------------------------------------------------------------------


1. What can it cache?
Common string, JsonObject, JsonArray, Bitmap, Drawable, serialized java object, and byte data.

2. What are its characteristics?
Main features:
1: Light, light to only one JAVA file.
2: configurable. You can configure the cache path, cache size, and cache quantity.
3: You can set the cache timeout time. The cache timeout value automatically expires and is deleted.
4: supports multiple processes.
3. What scenarios can it be used in android?
1. Replace SharePreference as the configuration file
2. Network request data can be cached. For example, the android client of oschina can cache the news content of http requests. The cache time is assumed to be 1 hour and will automatically expire after the timeout, allow the client to request new data to reduce Client Traffic and server concurrency.
3. For example...
4. How to Use ASimpleCache?
The following is a small demo that you would like:

ACache mCache = ACache. get (this );
MCache. put (test_key1, test value );
MCache. put (test_key2, test value, 10); // save for 10 seconds. If the key is obtained after 10 seconds, it is null.
MCache. put (test_key3, test value, 2 * ACache. TIME_DAY); // save for two days. If you get this key for more than two days, it is null.
Get Data

ACache mCache = ACache. get (this );
String value = mCache. getAsString (test_key1 );
 

Mainly analyzes the next collection of thousands of favoriteACache classTake string storage as an example)

First, create a cache

Get (Context ctx, String cacheName) method to create a cache directory

Get (File cacheDir, long max_zise, int max_count) method to create a cache instance and store it to the instance map. The key is the cache directory and the process id enabled for each application.

Public static ACache get (Context ctx) {return get (ctx, ACache);} public static ACache get (Context ctx, String cacheName) {// create a cache directory // data/com. yangfuhai. asimplecachedemo/cache/ACacheFile f = new File (ctx. getCacheDir (), cacheName); return get (f, MAX_SIZE, MAX_COUNT);} public static ACache get (File cacheDir) {return get (cacheDir, MAX_SIZE, MAX_COUNT );} public static ACache get (Context ctx, long max_z Ise, int max_count) {File f = new File (ctx. getCacheDir (), ACache); return get (f, max_zise, max_count);} public static ACache get (File cacheDir, long max_zise, int max_count) {// data/com. yangfuhai. asimplecachedemo/cache/ACacheACache manager = mInstanceMap. get (cacheDir. getAbsoluteFile () + myPid (); if (manager = null) {manager = new ACache (cacheDir, max_zise, max_count); // {/data/com. yangfuh Ai. asimplecachedemo/cache/acache_4133 = org. afinal. simplecache. ACache @ 2bc38270} // {/data/com. yangfuhai. asimplecachedemo/cache/ACache_12189 = org. afinal. simplecache. ACache @ 2bc3d890} mInstanceMap. put (cacheDir. getAbsolutePath () + myPid (), manager);} return manager;} private static String myPid () {return _ + android. OS. process. myPid ();} private ACache (File cacheDir, long max_size, int max_count) {if (! CacheDir. exists ()&&! CacheDir. mkdirs () {throw new RuntimeException (can't make dirs in + cacheDir. getAbsolutePath ();} mCache = new ACacheManager (cacheDir, max_size, max_count );}

 

2. Store Data

Put (String key, String value) method to write data to a file

The mCache. put (file) method in put (String key, String value) method has the following settings:

After the file is cached by the program, the total number of cached files, total number of cached files, and files are stored in the map file (the value is the last modification time of the file to facilitate destruction according to the preset destruction time)
If the cache does not exceed the limit, the total number of caches is increased.
When the cache exceeds the limit, the total number of caches is reduced.
The removeNext method is used to find the size of the oldest file.

public void put(String key, String value) {File file = mCache.newFile(key);BufferedWriter out = null;try {out = new BufferedWriter(new FileWriter(file), 1024);out.write(value);} catch (IOException e) {e.printStackTrace();} finally {if (out != null) {try {out.flush();out.close();} catch (IOException e) {e.printStackTrace();}}mCache.put(file);}}
// After the file is cached by the program, the total number of cached files, total number of cached files, and files are stored in the map file (the value is the last modification time of the file to facilitate destruction according to the preset destruction time) // If the cache does not exceed the limit, the total number of caches is increased. // if the total number of caches exceeds the limit, the total number of caches is reduced, value of the total number // The removeNext method is used to find the size of the oldest File private void put (file File) {int curCacheCount = cacheCount. get (); while (curCacheCount + 1> countLimit) {long freedSize = removeNext (); cacheSize. addAndGet (-freedSize); curCacheCount = cacheCount. addAndGet (-1);} cacheCount. addAndGet (1); long valueSize = calculateSize (file); long curCacheSize = cacheSize. get (); while (curCacheSize + valueSize> sizeLimit) {long freedSize = removeNext (); curCacheSize = cacheSize. addAndGet (-freedSize);} cacheSize. addAndGet (valueSize); Long currentTime = System. currentTimeMillis (); file. setLastModified (currentTime); lastUsageDates. put (file, currentTime );}

 

/*** Remove the old file (bubble, find the file with the minimum modification time) ** @ return */private long removeNext () {if (lastUsageDates. isEmpty () {return 0;} Long oldestUsage = null; File mostLongUsedFile = null; Set
 
  
> Entries = lastUsageDates. entrySet (); synchronized (lastUsageDates) {for (Entry
  
   
Entry: entries) {if (mostLongUsedFile = null) {mostLongUsedFile = entry. getKey (); oldestUsage = entry. getValue ();} else {Long lastValueUsage = entry. getValue (); if (lastValueUsage <oldestUsage) {oldestUsage = lastValueUsage; mostLongUsedFile = entry. getKey () ;}}} long fileSize = calculateSize (mostLongUsedFile); if (mostLongUsedFile. delete () {lastUsageDates. remove (mostLongUsedFile);} return fileSize ;}
  
 


3. obtain data

The getAsString (String key) method reads data from the cached file. The Utils. isDue (readString) method is used to determine whether the data has expired and whether to delete the data.

public String getAsString(String key) {///data/data/com.yangfuhai.asimplecachedemo/cache/ACache/1727748931File file = mCache.get(key);if (!file.exists())return null;boolean removeFile = false;BufferedReader in = null;try {in = new BufferedReader(new FileReader(file));String readString = ;String currentLine;while ((currentLine = in.readLine()) != null) {readString += currentLine;}if (!Utils.isDue(readString)) {return Utils.clearDateInfo(readString);} else {removeFile = true;return null;}} catch (IOException e) {e.printStackTrace();return null;} finally {if (in != null) {try {in.close();} catch (IOException e) {e.printStackTrace();}}if (removeFile)remove(key);}}

 

/*** Determine whether the cached String data expires ** @ param str * @ return true: expired; false: not expired */private static boolean isDue (String str) {return isDue (str. getBytes ();}/*** determines whether the cached byte data expires (Expiration: the current time is later than the storage time plus the retention time after the storage) ** @ param data * @ return true: expired; false: not expired */private static boolean isDue (byte [] data) {String [] strs = getDateInfoFromDate (data ); if (strs! = Null & strs. length = 2) {String saveTimeStr = strs [0]; while (saveTimeStr. startsWith (0) {saveTimeStr = saveTimeStr. substring (1, saveTimeStr. length ();} long saveTime = Long. valueOf (saveTimeStr); long deleteAfter = Long. valueOf (strs [1]); if (System. currentTimeMillis ()> saveTime + deleteAfter * 1000) {return true ;}} return false ;}
// Set private static boolean hasDateInfo (byte [] data) {return data! = Null & data. length> 15 & data [13] = '-' & indexOf (data, mSeparator)> 14 ;}// the saveDate file is saved in milliseconds, deleteAfter file retention time in milliseconds private static String [] getDateInfoFromDate (byte [] data) {if (hasDateInfo (data) {String saveDate = new String (copyOfRange (data, 0, 13); String deleteAfter = new String (copyOfRange (data, 14, indexOf (data, mSeparator); return new String [] {saveDate, deleteAfter };} return null ;}


 

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.