Learn more about Android Picture download framework Universialimageloader's disk cache extension (ii)

Source: Internet
Author: User

For the first article, this is about the continuation of the disk cache. Here we mainly focus on four categories, namely Disklrucache, Lrudiskcache, Strictlinereader and tools util.

The next step is to dissect them. Don't say much nonsense.

First look at Disklrucache.

What is the main function of this class? Let's take a look at a class of comments first:

/** * A cache that uses a bounded amount of space on A filesystem. Each cache * entry has a string key and a fixed number of values. Each key must match * the Regex <strong>[a-z0-9_-]{1,64}</strong>. Values are byte sequences, * accessible as streams or files. Each value must is between {@code 0} and * {@code integer.max_value} bytes in length. * <p>this class is tolerant of some I/O errors. If files is missing from the * filesystem, the corresponding entries would be dropped from the cache. If * An error occurs while writing a cache value, the edit would fail silently. * Callers should handle other problems by catching {@code IOException} and * responding appropriately. */
Not interested in English children's shoes don't worry, a little translation below:

This is a cache based on a limited space built by the file system. Each cache entry has a string secret key with a fixed number sequence. Each key must be matched with regular expression <strong>[a-z0-9_-]{1,64}</strong>. The value is a sequence of bytes that can be accessed as a stream or as a file. Each value must be between 0 and the largest integer in length. This cache class is tolerated for some of the I/O operating rooms. If some files are missing from the file system, the corresponding cached entry is removed from the cache. If an error occurs while writing a cached value,

The current edits are silently withdrawn, and the callback handles some of the other problems by capturing some I/O exceptions and verifying the response.

Since Disklrucache has a lot of code, we will tell it from some core variables and methods. The core variables are as follows:

Static final String journal_file = "JOURNAL"; static final String journal_file_temp = "Journal.tmp"; static final String JOU Rnal_file_backup = "JOURNAL.BKP"; static final String MAGIC = "Libcore.io.DiskLruCache"; static final String version_1 = "1" ; static final Long Any_sequence_number = -1;static final Pattern legal_key_pattern = Pattern.compile ("[a-z0-9_-]{1,64}") ;p rivate static final String clean = "clean";p rivate static final String DIRTY = "DIRTY";p rivate static final string Remov  E = "REMOVE";p rivate static final String read = "read";p rivate final file directory;private final file Journalfile;private  Final file journalfiletmp;private final file journalfilebackup;private final int appversion;private long maxsize;private int maxfilecount;private Final int valuecount;private long size = 0;private int filecount = 0;private Writer journalwrite R;private final linkedhashmap<string, entry> lruentries =new linkedhashmap<string, Entry> (0, 0.75f, true); private int REDUNDANTOPCOUNT;PRIvate long nextsequencenumber = 0;final threadpoolexecutor executorservice =new threadpoolexecutor (0, 1, 60L, TimeUnit.SE Conds, New linkedblockingqueue<runnable> ());

The above variables are broadly categorized, including: The name of the log file, the definition of the variable for the start of the log file in 5 rows, the size and number of the file, and a linkedhashmap to maintain a cache queue, and finally a thread pool.

The following is a general introduction to the functions inside:

1, readjournal This function is 1, calculates the current log cache row number, 2, calculates the current cache of the log file redundant rows 3, reads and processes the cached log of each row of data

2, Readjournalline This function is to actually perform the operation of each line of the log when a keyword is encountered in the log, from the current cache of the degree column to see whether the current keyword mapped objects exist, if not exist, Creates a new object with the current keyword and puts it into the current cached queue.

3. Processjournal calculates the size of the initialization and reclaims some of the garbage in the cache. Dirty entrances will be considered contradictory and will be recycled.

4, rebuildjournal This function is to create a new delete a large number of redundant information log files, if the current log file exists, will replace the current log file.

5.

Public synchronized Snapshot get (String key) throws IOException

The function is to return a snapshot of the file entry named key. And if the current value is returned, it will be moved to the head of the LRU queue.

6.

Public synchronized Boolean remove (String key) throws IOException

If the current file entity is present and can be deleted, then the entity of the current file is deleted. The file entity that is currently being edited is not able to be deleted.

Next, look at three of the more important inner classes in this class, snapshot, editor, and entry.

Provides a general description of the features of these three classes.

Snapshot is a snapshot of the value of the cached file entity. Editor is the numeric value of the file entity that edits the cache. Entry is the data model of the cached file entity.


Next we'll take a look at the main features of the Lrudiskcache class.

Like the name of this class, this is the most recently unused disk cache. So we know the approximate function of this class.

We will see such a member variable in this class

protected Disklrucache Cache;

This shows the current class, which is an adapter for the Disklrucache interface for the disk cache. Don't believe me? We can see from the following method:

1.

@Overridepublic File getdirectory () {return cache.getdirectory ();}

Gets the current cached directory.

2.

Public File get (String imageuri) {Disklrucache.snapshot Snapshot = null;try {Snapshot = Cache.get (GetKey (Imageuri)); return snapshot = = null? Null:snapshot.getFile (0);} catch (IOException e) {L.E (e); return null;} finally {if (snapshot! = null) {Snapshot.close ();}}}

Gets the handle to the picture file through the object of the URI of the picture. is implemented through snapshots in Disklrucache.


3.

Public boolean Save (String Imageuri, InputStream ImageStream, Ioutils.copylistener listener) throws IOException { Disklrucache.editor editor = Cache.edit (GetKey (Imageuri)); if (Editor = = null) {return false;} OutputStream OS = new Bufferedoutputstream (editor.newoutputstream (0), buffersize); Boolean copied = false;try {copied = Io Utils.copystream (ImageStream, OS, Listener, buffersize);} finally {ioutils.closesilently (OS), if (copied) {Editor.commit ();} else {editor.abort ();}} return copied;}

Using the File Editor class editor in Disklrucache, the current file input stream is written to the generated file.

The rest of the functions are also and so on.


Next to the class Strictlinereader, we can also understand it as a helper class, which is specifically designed to read the contents of the cache log.

Observe one of the following methods:

Public String ReadLine () throws IOException {synchronized (in) {if (buf = = null) {throw new IOException ("Linereader is CLO Sed ");} if (pos >= end) {fillbuf ();} for (int i = pos; I! = end; ++i) {if (buf[i] = = LF) {int lineend = (i! = pos && buf[i-1] = = CR)? i-1: i; string res = new String (buf, POS, Lineend-pos, Charset.name ());p OS = i + 1;return res;}} Bytearrayoutputstream out = new Bytearrayoutputstream (End-pos +) {@Overridepublic String toString () {int length = (Co Unt > 0 && buf[count-1] = = CR)? Count-1: count;try {return new String (buf, 0, length, charset.name ());} catch (Unsupportedencodingexception e) {throw n EW Assertionerror (e); Since We control the charset this would never happen.}}}; while (true) {Out.write (buf, POS, end-pos);//Mark unterminated line in case Fillbuf throws Eofexception or IOException. End = -1;fillbuf (); for (int i = pos; I! = end; ++i) {if (buf[i] = = LF) {if (i! = pos) {out.write (buf, POS, i-pos);} pos = i + 1;return out. toString ();}}}} 


In the last class Util, three methods are encapsulated,

1. readfully reads the content from reader and stitching it into a complete string

2, deletecontents the contents of the directory to delete files

3. closequietly Silent Close File stream


Ok, about the expansion of disk storage here, I hope you can help children's shoes.












Learn more about Android Picture download framework Universialimageloader's disk cache extension (ii)

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.