Basics: LRU cache algorithm

1. Prospect

        When the cache function is used in the Android development process, its memory and storage space are generally limited. When a new element is inserted and the space used is limited, the old element needs to be eliminated.

Two, LRU cache        

        It is a cache elimination strategy, the full name is least recently used , which means least recently used

        Main idea: If a piece of data was accessed recently, it may still be accessed in the future. When a certain threshold is reached, the data that has not been accessed recently is eliminated, so as to ensure that the amount of cached data will not be too large

3. Implementation method

  1. Use linked list to achieve
  2. There is new data added, insert the chain head
  3. If used in the cache, move the fetched data to the head of the chain
  4. When the linked list is full, the data at the end of the chain is discarded

4. LruCache  

Image cache elimination strategy

  1. Set the maximum capacity limit through the constructor
  2. Data storage through LinkedHashMap
  3. Read the cache through the get method, and lock the thread-safe code blocks through synchronized to ensure the thread safety of the read operation here
  4. Write the cache through the put method, and put the data into the Map. If there is data at the previous key position, subtract the original size from the current size to calculate the put size.
  5. Afterwards,  trimToSize the space is reorganized through the method, and the previous elements in the Map are continuously deleted through the remove method until the size is less than maxSize, thereby realizing the space reorganization.

 Five, DiskLruCache

An open source library that implements LRU storage on disk

Guess you like

Origin blog.csdn.net/weixin_42277946/article/details/130220350