Android implements data _android such as cached images

Source: Internet
Author: User
Tags stub wrapper

The

uses the Linkedhashmap LRU algorithm to cache data, detects if the object has been reclaimed by the virtual machine, recalculates the current cache size, and clears unused key-value objects in the cache (that is, data that has been reclaimed by the virtual machine but not purged from the cache);
 * The default memory cache size is: 4 * 1024 * 1024 You can manually empty the memory cache by setmaxcachesize the cache size by using the
 * <br> support memory cache and disk caching via {@link cc.util. Cache. Netbytewrapper} supports HTTP caching (note: detailed reference cc.util.http package); Note: Use JDK7

Package Cc.util.cache;
Import java.io.Serializable;
 
Import java.util.Objects; /** encapsulates the network data, obtains the data etag, lastmodified, and extracts it to the server at the next request, to wrap the byte data which obtains from network, it will Wo  RK with {@link Cc.util.cache.NetChacheManager} * @author Wangcccong * @version 1.1406 * <br> Create at:tues, 10
 
  June 2014 */public class Netbytewrapper implements Serializable {Private final static long serialversionuid = 1L;
  /** Data from Network * * Private byte[] data;
  /** data size */int contentlength;
  /** latested Modify Time */private long lastmodified;
 
  /** Etag:look up HTTP Protocol */private String ETag;
    Public Netbytewrapper (byte[] data, long lastmodified, String Etag) {this.data = data;
    this.lastmodified = LastModified; This.
  ETag = ETag;
  Byte[] GetData () {return data;
  public void SetData (byte[] data) {this.data = data;
  Public long getlastmodified () {return lastmodified;
 } public void setlastmodified (long lastmodified) {this.lastmodified = LastModified;
  Public String Getetag () {return ETag; } public void Setetag (String eTag) {this.
  ETag = ETag;
  public int getcontentlength () {return objects.isnull (data) 0:data.length;
 
}} package Cc.util.cache;
Import Java.lang.ref.ReferenceQueue;
 
Import java.lang.ref.SoftReference; /** use soft reference to store data * Enclose {@link Cc.util.cache.NetByteWrapper} with {@link java.lang.ref.SoftReference}. Cycle the memory * @author Wangcccong * @version 1.1406 * <br> Create at:tues, June 2014/public class Net
  Bytesoftreference extends softreference<netbytewrapper> {private String key = "";
 
  Private long length = 0;
  Public netbytesoftreference (String key, Netbytewrapper arg0) {This (key, arg0, NULL); Public netbytesoftreference (String key, Netbytewrapper arg0, referencequeue<? Super netbytewrapper> Arg1
   ) { Super (arg0, arg1);
    TODO auto-generated constructor stub this.key = key;
  This.length = Arg0.getcontentlength ();
  Public String Getkey () {return key;
  Public long GetLength () {return length;
 
}} package Cc.util.cache;
Import Java.lang.ref.ReferenceQueue;
Import java.lang.ref.SoftReference;
Import Java.io.FileInputStream;
Import Java.io.FileOutputStream;
Import Java.io.ObjectInputStream;
Import Java.io.ObjectOutputStream;
Import Java.util.Iterator;
Import Java.util.LinkedHashMap;
 
Import java.util.Objects; /** * uses the LINKEDHASHMAP's own LRU algorithm to cache data, detects whether an object has been reclaimed by the virtual machine, recalculates the current cache size, and clears the unused key-value objects in the cache (that is, data that has been reclaimed by the virtual machine but not purged from the cache); * Default memory Cache Size: 4 * 102 4 * 1024 by setmaxcachesize The cache size, you can manually empty the memory cache, support the memory-mapped way to read the cache * <br> support memory cache and disk caching, via {@link  Cc.util.cache.NetByteWrapper} supports HTTP caching (note: detailed reference cc.util.http package) * @author Wangcccong * @version 1.1406 * <br> Create At:tues June 2014/public class Netcachemanager {/** max cache size * * * privatE Long max_cache_size = 4 * 1024 * 1024; 
 
  Private long cacheSize = 0;
   
  private static Netcachemanager instance = NULL;
  Private final referencequeue<netbytewrapper> Referencequeue;
   
  Private final linkedhashmap<string, netbytesoftreference> Cachemap;
    Private Netcachemanager () {referencequeue = new referencequeue<netbytewrapper> (); Cachemap = new linkedhashmap<string, netbytesoftreference> (0.75f, true) {private static final long Seri
      Alversionuid = -8378285623387632829l; @Override protected Boolean removeeldestentry (java.util.map.entry<string, netbytesoftreference> eld
        EST) {//TODO auto-generated Method Stub Boolean shouldremove = CacheSize > max_cache_size;
          if (shouldremove) {cacheSize-= Eldest.getvalue (). GetLength ();
        System.GC ();
      return shouldremove;
  }
    }; /** Singleton model */public static synchronized NetcAchemanager newinstance () {if (Objects.isnull (instance)) {instance = new Netcachemanager ();
  return instance;
    /** * Reset the memory cache size * @param cacheSize/public void setmaxcachesize (long cacheSize) { This.
  Max_cache_size = cacheSize;
  /** * Get current memory Cache size * @return/public long getcachesize () {return cacheSize;
   /** * Caches data to memory, and if HTTP returns data <b> does not support </b> caching, this method is used, and the cached key is typically the requested URL * @param key * @param value
  */public void cacheinmemory (String key, byte[] value) {this.cacheinmemory (key, value, 0, NULL); /** * Caches data to memory, if HTTP returns data <b> support </b> Caching this method * @param key * @param value * @param lastmodi fied */public void cacheinmemory (String key, byte[] value, long lastmodified) {this.cacheinmemory (key, value, L
  Astmodified, NULL); /** * Caches data to memory, using this method @param key * @param value if HTTP returns data <b> support </b> caching @paraM Etags */public void Cacheinmemory (string key, byte[] value, String Etags) {this.cacheinmemory (key, value, 0,
  Etags); /** * Caches data to memory, if HTTP returns data <b> support </b> Caching this method * @param key * @param value * @param lastmodi
    fied * @param Etags * * private void Cacheinmemory (String key, byte[] value, long lastmodified, String Etags) {
    Objects.requirenonnull (Key, "key must not being null");
    Clearrecycledobject ();
    Netbytewrapper wrapper = new Netbytewrapper (value, LastModified, Etags);
    Netbytesoftreference byteref = new Netbytesoftreference (key, wrapper, Referencequeue);
    Cachemap.put (key, Byteref);
    value = NULL;
  wrapper = null; /** * Cache to disk, default is not first cached to memory * @param key * @param value * @param path/public void Cacheindisk (stri
  ng key, byte[] value, String path) {Cacheindisk (key, value, path, false); /** * * @param key * @param value * @param path * @param cacheinmemory * *
  public void Cacheindisk (string key, byte[] value, String path, Boolean cacheinmemory) {This.cacheindisk (key, value
  , 0, NULL, path, cacheinmemory); /** * * @param key * @param value * @param lastmodified * @param Etags * @param path * @para M cacheinmemory */private void Cacheindisk (string key, byte[] value, long lastmodified, string Etags, string path, b
    Oolean cacheinmemory) {if (cacheinmemory) cacheinmemory (key, value, LastModified, Etags);
        Try (fileoutputstream fos = new FileOutputStream (path); ObjectOutputStream oos = new ObjectOutputStream (FOS)) {Netbytewrapper wrapper = new Netbytewrapper (value, Lastmod
        Ified, Etags);
    Oos.writeobject (wrapper);
    catch (Exception e) {//Todo:handle Exception e.printstacktrace (); }/** * get {@link Cc.util.cache.NetByteWrapper} from memory according to key * @param key * @return {@ Link Cc.util.cache.NetByteWrapper} */PublicNetbytewrapper getfrommemory (String key) {softreference<netbytewrapper> softreference = CacheMap.get (key); Return Objects.nonnull (softreference)?
  Softreference.get (): null; /** * Get byte[] from memory according to key * @param context * @param key * @return/public b
    Yte[] Getbytefrommemory (String key) {Netbytewrapper wrapper = getfrommemory (key); return Objects.nonnull (wrapper)?
  Wrapper.getdata (): null; /** * Get data from disk * @param path * @return {@link Cc.util.cache.NetByteWrapper}/Public Netbytewrapper
        Getfromdisk (String path) {try (FileInputStream fis = new FileInputStream (path);
      ObjectInputStream ois = new ObjectInputStream (FIS)) {Netbytewrapper wrapper = (netbytewrapper) ois.readobject ();
    return wrapper;
      catch (Exception e) {//Todo:handle Exception e.printstacktrace ();
    return null; }/** * Fetching data from disk in memory-mapped (faster reading of cached large files) * @param path
   * @return */public netbytewrapper getfromdiskbymapped (String path) {try (FileInputStream fis = new Fileinpu
        Tstream (path);
        FileChannel channel= Fis.getchannel (); Bytearrayoutputstream BAOs = new Bytearrayoutputstream ()) {Mappedbytebuffer MBB = Channel.map (FileChannel.MapMode.RE
      Ad_only, 0, Channel.size ()); 
      byte[] BTS = new byte[1024];
      int len = (int) channel.size ();
        for (int offset = 0; offset < len; offset + = 1024) {if (Len-offset > 1024) mbb.get (BTS); 
        else Mbb.get (BTS = new Byte[len-offset]);
      Baos.write (BTS);
      } bytearrayinputstream Bais = new Bytearrayinputstream (Baos.tobytearray ());
      ObjectInputStream ois = new ObjectInputStream (Bais);
      Netbytewrapper wrapper = (netbytewrapper) ois.readobject ();
      Bais.close ();
      Ois.close ();
    return wrapper;
      catch (Exception e) {//Todo:handle Exception e.printstacktrace ();
    return null; }
  }
   
  /** * byte[] Data cached from disk * @param path * @return/public byte[] Getbytefromdisk (String path) {N
    Etbytewrapper wrapper = getfromdisk (path); return Objects.isnull (wrapper)?
  Null:wrapper.getData (); /** * byte[data cached from disk via memory map * @param path * @return/public byte[] getbytefromdiskbymapped (Str
    ing path) {Netbytewrapper wrapper = getfromdiskbymapped (path); return Objects.isnull (wrapper)?
  Null:wrapper.getData (); }/** * Calculate the size of the cache memory/private void Clearrecycledobject () {Netbytesoftrefere
    NCE ref = NULL; Detects if the object is reclaimed and removes the dead item from the cache if it is reclaimed (objects.nonnull (ref = (netbytesoftreference) referencequeue.poll ())) {Cache
    Map.Remove (Ref.getkey ());
    } cacheSize = 0;
    iterator<string> keys = Cachemap.keyset (). iterator ();
    while (Keys.hasnext ()) {cacheSize + = Cachemap.get (Keys.next ()). GetLength ();
 }/** * Clear the memory cache  */public void ClearCache () {clearrecycledobject ();
    Cachemap.clear ();
    System.GC ();
  System.runfinalization ();
 }
   
}

The above is the entire contents of this article, I hope you can enjoy.

Related Article

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.