> Java > java지도 시간 > 본문

Java 및 Android의 LRU 캐시 및 구현 원리

黄舟
풀어 주다: 2017-02-20 10:29:00
원래의
1467명이 탐색했습니다.

1. 개요

Android에서는 LRU 알고리즘의 캐싱을 구현하는 데 편리하게 사용할 수 있는 LRUCache 클래스를 제공합니다. Java는 LRU 알고리즘을 쉽게 구현할 수 있는 LinkedHashMap을 제공합니다. Java의 LRULinkedHashMap은 LinkedHashMap을 직접 상속하므로 거의 변경하지 않고도 LRU 알고리즘을 구현할 수 있습니다.

2. Java의 LRU 알고리즘

LinkedHashMap은 HashMap을 상속받아 LRU 알고리즘을 구현합니다.

1. HashMap

가장 먼저 주목해야 할 점은 HashMap이 Entry Entry는 해당 노드에 해당하는 키, 값, 해시 정보를 저장하고, 현재 노드의 다음 노드에 대한 참조도 저장합니다. 따라서 Entry는 단방향 연결 목록입니다. HashMap의 저장 구조는 배열과 단방향 연결 목록의 형태입니다. 각 키에 해당하는 hashCode는 HashMap 배열의 한 위치에서 찾을 수 있으며, 여러 키가 동일한 hashCode에 해당하면 이 때 HashMap은 해당 정보를 저장합니다. 이를 Entry에 넣고, 연결리스트를 이용하여 이들 Entry를 연결합니다.

 static class Entry<K,V> implements Map.Entry<K,V> {
        final K key;
        V value;
        Entry<K,V> next;
        int hash;
        /**
         * Creates new entry.
         */
        Entry(int h, K k, V v, Entry<K,V> n) {
            value = v;
            next = n;
            key = k;
            hash = h;
        }
        public final K getKey() {
            return key;
        }
        public final V getValue() {
            return value;
        }
        public final V setValue(V newValue) {
            V oldValue = value;
            value = newValue;
            return oldValue;
        }
        public final boolean equals(Object o) {
            if (!(o instanceof Map.Entry))
                return false;
            Map.Entry e = (Map.Entry)o;
            Object k1 = getKey();
            Object k2 = e.getKey();
            if (k1 == k2 || (k1 != null && k1.equals(k2))) {
                Object v1 = getValue();
                Object v2 = e.getValue();
                if (v1 == v2 || (v1 != null && v1.equals(v2)))
                    return true;
            }
            return false;
        }
        public final int hashCode() {
            return Objects.hashCode(getKey()) ^ Objects.hashCode(getValue());
        }
        public final String toString() {
            return getKey() + "=" + getValue();
        }
        /**
         * This method is invoked whenever the value in an entry is
         * overwritten by an invocation of put(k,v) for a key k that&#39;s already
         * in the HashMap.
         */
        void recordAccess(HashMap<K,V> m) {
        }
        /**
         * This method is invoked whenever the entry is
         * removed from the table.
         */
        void recordRemoval(HashMap<K,V> m) {
        }
    }
로그인 후 복사

아래 HashMap의 put 메소드 코드를 게시하고 분석해 보세요.

 

public V put(K key, V value) {
        if (table == EMPTY_TABLE) {
            inflateTable(threshold);
        }
        if (key == null)
            return putForNullKey(value);
     //以上信息不关心,下面是正常的插入逻辑。
     //首先计算hashCode
        int hash = hash(key);
     //通过计算得到的hashCode,计算出hashCode在数组中的位置
        int i = indexFor(hash, table.length);
     //for循环,找到在HashMap中是否存在一个节点,对应的key与传入的key完全一致。如果存在,说明用户想要替换该key对应的value值,因此直接替换value即可返回。
        for (Entry<K,V> e = table[i]; e != null; e = e.next) {
            Object k;
            if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
                V oldValue = e.value;
                e.value = value;
                e.recordAccess(this);
                return oldValue;
            }
        }
     //逻辑执行到此处,说明HashMap中不存在完全一致的kye.调用addEntry,新建一个节点保存key、value信息,并增加到HashMap中
        modCount++;
        addEntry(hash, key, value, i);
        return null;
    }
로그인 후 복사

위 코드에 코멘트를 추가하면 이해가 되실 겁니다. 전체의. 분석할 가치가 있는 몇 가지 사항은 아래에 자세히 설명되어 있습니다.

<1> int i = indexFor(hash, table.length);
로그인 후 복사

소스 코드를 살펴보세요:

 

static int indexFor(int h, int length) {
        // assert Integer.bitCount(length) == 1 : "length must be a non-zero power of 2";
        return h & (length-1);
    }
로그인 후 복사

얻어진 hashCode(h)를 비트 단위 AND로 연결해야 하는 이유는 무엇입니까? (길이-1) ? 이는 h의 상위 정보가 제거되었는지 확인하기 위한 것입니다. 배열 크기가 8(1000)이고 계산된 h 값이 10(1010)인 경우 배열 인덱스가 10인 데이터를 직접 가져오면 배열 범위를 벗어난 예외가 발생합니다. 따라서 비트별 AND(0111&1010)를 이용하면 상위 정보는 성공적으로 클리어되어 2(0010)를 얻게 되는데, 이는 해당 배열에서 인덱스가 2인 데이터를 의미한다. 효과는 나머지와 동일하지만 비트 연산이 훨씬 더 효율적입니다.

그러나 여기에는 문제가 있다. 길이가 9라면 얻는 길이-1 정보는 8(1000)이다. 지워졌지만 얻은 결과는 확실히 잘못된 것입니다. 따라서 배열의 크기에는 뭔가 특별한 것이 있어야 합니다. 소스 코드를 보면 HashMap이 해당 배열의 수가 항상 2의 n승임을 보장한다는 것을 알 수 있습니다.

먼저 퍼팅 시 inflateTable 메소드를 호출합니다. 초점은 roundUpToPowerOf2 메서드에 있습니다. 해당 내용에는 많은 수의 비트 관련 작업 및 처리가 포함되어 있지만 이는 명확하지 않지만 주석에서는 배열 수가 2에서 n번째로 증가하도록 보장한다는 점을 분명히 했습니다. 힘.

private void inflateTable(int toSize) {
// Find a power of 2 >= toSize
int capacity = roundUpToPowerOf2(toSize);
threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
table = new Entry[capacity];
initHashSeedAsNeeded(capacity);
}
로그인 후 복사

두 번째로 addEntry, (2 * table.length), table.length << 1과 같은 다른 방법도 숫자를 확인하는 데 사용됩니다. 배열의 2n승은 입니다.

<2> for (Entry<K,V> e = table[i]; e != null; e = e.next)
로그인 후 복사

HashMap은 배열과 연결 리스트의 형태를 사용하기 때문에 hashCode를 통해 배열의 위치를 ​​얻은 후 얻는 것은 Entry가 아니라 For입니다. Entry의 연결 목록을 사용하려면 연결 목록을 반복하여 키에 해당하는 값을 얻어야 합니다.

<3> addEntry(hash, key, value, i);
로그인 후 복사

먼저 어레이 수가 임계값을 초과하는지 확인합니다. 그렇다면 어레이 수를 늘려야 합니다. 그런 다음 새 항목이 생성되어 배열에 추가됩니다.

/**
     * Adds a new entry with the specified key, value and hash code to
     * the specified bucket.  It is the responsibility of this
     * method to resize the table if appropriate.
     *
     * Subclass overrides this to alter the behavior of put method.
     */
    void addEntry(int hash, K key, V value, int bucketIndex) {
        if ((size >= threshold) && (null != table[bucketIndex])) {
            resize(2 * table.length);
            hash = (null != key) ? hash(key) : 0;
            bucketIndex = indexFor(hash, table.length);
        }
        createEntry(hash, key, value, bucketIndex);
    }
    /**
     * Like addEntry except that this version is used when creating entries
     * as part of Map construction or "pseudo-construction" (cloning,
     * deserialization).  This version needn&#39;t worry about resizing the table.
     *
     * Subclass overrides this to alter the behavior of HashMap(Map),
     * clone, and readObject.
     */
    void createEntry(int hash, K key, V value, int bucketIndex) {
        Entry<K,V> e = table[bucketIndex];
        table[bucketIndex] = new Entry<>(hash, key, value, e);
        size++;
    }
로그인 후 복사

2. LinkedHashMap

LinkedHashMap은 HashMap을 기반으로 수정되었습니다. 먼저 항목을 단방향 연결 목록에서 이중 연결 목록으로 변경합니다. 팀 참가 전후에 대한 참조를 추가했습니다.

  private static class Entry<K,V> extends HashMap.Entry<K,V> {
        // These fields comprise the doubly linked list used for iteration.
        Entry<K,V> before, after;
        Entry(int hash, K key, V value, HashMap.Entry<K,V> next) {
            super(hash, key, value, next);
        }
        /**
         * Removes this entry from the linked list.
         */
        private void remove() {
            before.after = after;
            after.before = before;
        }
        /**
         * Inserts this entry before the specified existing entry in the list.
         */
        private void addBefore(Entry<K,V> existingEntry) {
            after  = existingEntry;
            before = existingEntry.before;
            before.after = this;
            after.before = this;
        }
        /**
         * This method is invoked by the superclass whenever the value
         * of a pre-existing entry is read by Map.get or modified by Map.set.
         * If the enclosing Map is access-ordered, it moves the entry
         * to the end of the list; otherwise, it does nothing.
         */
        void recordAccess(HashMap<K,V> m) {
            LinkedHashMap<K,V> lm = (LinkedHashMap<K,V>)m;
            if (lm.accessOrder) {
                lm.modCount++;
                remove();
                addBefore(lm.header);
            }
        }
        void recordRemoval(HashMap<K,V> m) {
            remove();
        }
    }
로그인 후 복사

동시에 LinkedHashMap은 Entry에 참조 헤더(비공개 임시 Entry 헤더)를 제공합니다. 헤더의 기능은 항상 HashMap의 모든 멤버의 헤드(header.after)와 테일(header.before)입니다. 이런 식으로 HashMap 자체의 배열 및 연결 목록 형식이 수정됩니다. LinkedHashMap에서는 HashMap의 배열과 연결 목록의 데이터 저장 형식이 유지되고 헤더가 시작 마커인 이중 연결 목록 세트(일시적으로 헤더 이중 연결 목록이라고 부름)가 추가됩니다. LinkedHashMap은 헤더의 이중 연결 목록을 통해 LRU 알고리즘을 구현합니다. header.after는 항상 최근에 가장 적게 사용된 노드를 가리킵니다. 삭제되면 header.after에 해당하는 노드가 삭제됩니다. 대조적으로, header.before는 방금 사용된 노드를 가리킵니다.

LinkedHashMap은 put 메소드를 제공하지 않지만 LinkedHashMap은 addEntry 및 createEntry 메소드를 다음과 같이 다시 작성합니다.

 /**
     * This override alters behavior of superclass put method. It causes newly
     * allocated entry to get inserted at the end of the linked list and
     * removes the eldest entry if appropriate.
     */
    void addEntry(int hash, K key, V value, int bucketIndex) {
        super.addEntry(hash, key, value, bucketIndex);
        // Remove eldest entry if instructed
        Entry<K,V> eldest = header.after;
        if (removeEldestEntry(eldest)) {
            removeEntryForKey(eldest.key);
        }
    }
    /**
     * This override differs from addEntry in that it doesn&#39;t resize the
     * table or remove the eldest entry.
     */
    void createEntry(int hash, K key, V value, int bucketIndex) {
        HashMap.Entry<K,V> old = table[bucketIndex];
        Entry<K,V> e = new Entry<>(hash, key, value, old);
        table[bucketIndex] = e;
        e.addBefore(header);
        size++;
    }
로그인 후 복사

HashMap의 put 메소드는 addEntry의 put 메소드를 호출합니다. addEntry 메소드는 createEntry 메소드를 호출합니다. 따라서 위의 두 가지 방법을 HashMap의 콘텐츠와 결합하여 분석을 용이하게 하여 다음 방법을 구성할 수 있습니다.

 

void addEntry(int hash, K key, V value, int bucketIndex) {
        if ((size >= threshold) && (null != table[bucketIndex])) {
            resize(2 * table.length);
            hash = (null != key) ? hash(key) : 0;
            bucketIndex = indexFor(hash, table.length);
        }
        HashMap.Entry<K,V> old = table[bucketIndex];
        Entry<K,V> e = new Entry<>(hash, key, value, old);
        table[bucketIndex] = e;
        e.addBefore(header);
        size++;
        // Remove eldest entry if instructed
        Entry<K,V> eldest = header.after;
        if (removeEldestEntry(eldest)) {
            removeEntryForKey(eldest.key);
        }
    }
로그인 후 복사

同样,先判断是否超出阈值,超出则增加数组的个数。然后创建Entry对象,并加入到HashMap对应的数组和链表中。与HashMap不同的是LinkedHashMap增加了e.addBefore(header);和removeEntryForKey(eldest.key);这样两个操作。

首先分析一下e.addBefore(header)。其中e是LinkedHashMap.Entry对象,addBefore代码如下,作用就是讲header与当前对象相关联,使当前对象增加到header的双向链表的尾部

(header.before):
    private void addBefore(Entry<K,V> existingEntry) {
            after  = existingEntry;
            before = existingEntry.before;
            before.after = this;
            after.before = this;
        }
로그인 후 복사

其次是另一个重点,代码如下:

  // Remove eldest entry if instructed
        Entry<K,V> eldest = header.after;
        if (removeEldestEntry(eldest)) {
            removeEntryForKey(eldest.key);
        }
로그인 후 복사

其中,removeEldestEntry判断是否需要删除最近最不常使用的那个节点。LinkedHashMap中的removeEldestEntry(eldest)方法永远返回false,如果我们要实现LRU算法,就需要重写这个方法,判断在什么情况下,删除最近最不常使用的节点。removeEntryForKey的作用就是将key对应的节点在HashMap的数组加链表结构中删除,源码如下:

  

final Entry<K,V> removeEntryForKey(Object key) {
        if (size == 0) {
            return null;
        }
        int hash = (key == null) ? 0 : hash(key);
        int i = indexFor(hash, table.length);
        Entry<K,V> prev = table[i];
        Entry<K,V> e = prev;
        while (e != null) {
            Entry<K,V> next = e.next;
            Object k;
            if (e.hash == hash &&
                ((k = e.key) == key || (key != null && key.equals(k)))) {
                modCount++;
                size--;
                if (prev == e)
                    table[i] = next;
                else
                    prev.next = next;
                e.recordRemoval(this);
                return e;
            }
            prev = e;
            e = next;
        }
        return e;
    }
로그인 후 복사

removeEntryForKey是HashMap的方法,对LinkedHashMap中header的双向链表无能为力,而LinkedHashMap又没有重写这个方法,那header的双向链表要如何处理呢。

仔细看一下代码,可以看到在成功删除了HashMap中的节点后,调用了e.recordRemoval(this);方法。这个方法在HashMap中为空,LinkedHashMap的Entry则实现了这个方法。其中remove()方法中的两行代码为双向链表中删除当前节点的标准代码,不解释。

/**
         * Removes this entry from the linked list.
         */
        private void remove() {
            before.after = after;
            after.before = before;
        }void recordRemoval(HashMap<K,V> m) {
            remove();
        }
로그인 후 복사

以上,LinkedHashMap增加节点的代码分析完毕,可以看到完美的将新增的节点放在了header双向链表的末尾。

但是,这样显然是先进先出的算法,而不是最近最不常使用算法。需要在get的时候,更新header双向链表,把刚刚get的节点放到header双向链表的末尾。我们来看看get的源码:

  public V get(Object key) {
        Entry<K,V> e = (Entry<K,V>)getEntry(key);
        if (e == null)
            return null;
        e.recordAccess(this);
        return e.value;
    }
로그인 후 복사

代码很短,第一行的getEntry调用的是HashMap的getEntry方法,不需要解释。真正处理header双向链表的代码是e.recordAccess(this)。看一下代码:

    

 /**
         * Removes this entry from the linked list.
         */
        private void remove() {
            before.after = after;
            after.before = before;
        }
        /**
         * Inserts this entry before the specified existing entry in the list.
         */
        private void addBefore(Entry<K,V> existingEntry) {
            after  = existingEntry;
            before = existingEntry.before;
            before.after = this;
            after.before = this;
        }
        /**
         * This method is invoked by the superclass whenever the value
         * of a pre-existing entry is read by Map.get or modified by Map.set.
         * If the enclosing Map is access-ordered, it moves the entry
         * to the end of the list; otherwise, it does nothing.
         */
        void recordAccess(HashMap<K,V> m) {
            LinkedHashMap<K,V> lm = (LinkedHashMap<K,V>)m;
            if (lm.accessOrder) {
                lm.modCount++;
                remove();
                addBefore(lm.header);
            }
        }
로그인 후 복사

首先在header双向链表中删除当前节点,再将当前节点添加到header双向链表的末尾。当然,在调用LinkedHashMap的时候,需要将accessOrder设置为true,否则就是FIFO算法。

三、Android的LRU算法

Android同样提供了HashMap和LinkedHashMap,而且总体思路有些类似,但是实现的细节明显不同。而且Android提供的LruCache虽然使用了LinkedHashMap,但是实现的思路并不一样。Java需要重写removeEldestEntry来判断是否删除节点;而Android需要重写LruCache的sizeOf,返回当前节点的大小,Android会根据这个大小判断是否超出了限制,进行调用trimToSize方法清除多余的节点。

Android的sizeOf方法默认返回1,默认的方式是判断HashMap中的数据个数是否超出了设置的阈值。也可以重写sizeOf方法,返回当前节点的大小。Android的safeSizeOf会调用sizeOf方法,其他判断阈值的方法会调用safeSizeOf方法,进行加减操作并判断阈值。进而判断是否需要清除节点。

Java的removeEldestEntry方法,也可以达到同样的效果。Java需要使用者自己提供整个判断的过程,两者思路还是有些区别的。

sizeOf,safeSizeOf不需要说明,而put和get方法,虽然和Java的实现方式不完全一样,但是思路是相同的,也不需要分析。在LruCache中put方法的最后,会调用trimToSize方法,这个方法用于清除超出的节点。它的代码如下:

 

 public void trimToSize(int maxSize)
  {
    while (true)
    {
      Object key;
      Object value;
      synchronized (this) {
        if ((this.size < 0) || ((this.map.isEmpty()) && (this.size != 0))) {
          throw new IllegalStateException(getClass().getName() + ".sizeOf() is reporting inconsistent results!");
        }
      if (size <= maxSize) {
        break;
      }
        Map.Entry toEvict = (Map.Entry)this.map.entrySet().iterator().next();
        key = toEvict.getKey();
        value = toEvict.getValue();
        this.map.remove(key);
        this.size -= safeSizeOf(key, value);
        this.evictionCount += 1;
      }
      entryRemoved(true, key, value, null);
    }
  }
로그인 후 복사

重点需要说明的是Map.Entry toEvict = (Map.Entry)this.map.entrySet().iterator().next();这行代码。它前面的代码判断是否需要删除最近最不常使用的节点,后面的代码用于删除具体的节点。这行代码用于获取最近最不常使用的节点。

首先需要说明的问题是,Android的LinkedHashMap和Java的LinkedHashMap在思路上一样,也是使用header保存双向链表。在put和get的时候,会更新对应的节点,保存header.after指向最久没有使用的节点;header.before用于指向刚刚使用过的节点。所以Map.Entry toEvict = (Map.Entry)this.map.entrySet().iterator().next();这行最终肯定是获取header.after节点。下面逐步分析代码,就可以看到是如何实现的了。

首先,map.entrySet(),HashMap定义了这个方法,LinkedHashMap没有重写这个方法。因此调用的是HashMap对应的方法:

  

public Set<Entry<K, V>> entrySet() {
        Set<Entry<K, V>> es = entrySet;
        return (es != null) ? es : (entrySet = new EntrySet());
    }
로그인 후 복사

上面代码不需要细说,new一个EntrySet类的实例。而EntrySet也是在HashMap中定义,LinkedHashMap中没有。

  

private final class EntrySet extends AbstractSet<Entry<K, V>> {
        public Iterator<Entry<K, V>> iterator() {
            return newEntryIterator();
        }
        public boolean contains(Object o) {
            if (!(o instanceof Entry))
                return false;
            Entry<?, ?> e = (Entry<?, ?>) o;
            return containsMapping(e.getKey(), e.getValue());
        }
        public boolean remove(Object o) {
            if (!(o instanceof Entry))
                return false;
            Entry<?, ?> e = (Entry<?, ?>)o;
            return removeMapping(e.getKey(), e.getValue());
        }
        public int size() {
            return size;
        }
        public boolean isEmpty() {
            return size == 0;
        }
        public void clear() {
            HashMap.this.clear();
        }
    }
로그인 후 복사

  Iterator> newEntryIterator() { return new EntryIterator(); }
代码中很明显的可以看出,Map.Entry toEvict = (Map.Entry)this.map.entrySet().iterator().next(),就是要调用newEntryIterator().next(),就是调用(new EntryIterator()).next()。而EntryIterator类在LinkedHashMap中是有定义的。

  

private final class EntryIterator
            extends LinkedHashIterator<Map.Entry<K, V>> {
        public final Map.Entry<K, V> next() { return nextEntry(); }
    }
    private abstract class LinkedHashIterator<T> implements Iterator<T> {
        LinkedEntry<K, V> next = header.nxt;
        LinkedEntry<K, V> lastReturned = null;
        int expectedModCount = modCount;
        public final boolean hasNext() {
            return next != header;
        }
        final LinkedEntry<K, V> nextEntry() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            LinkedEntry<K, V> e = next;
            if (e == header)
                throw new NoSuchElementException();
            next = e.nxt;
            return lastReturned = e;
        }
        public final void remove() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            if (lastReturned == null)
                throw new IllegalStateException();
            LinkedHashMap.this.remove(lastReturned.key);
            lastReturned = null;
            expectedModCount = modCount;
        }
    }
로그인 후 복사

现在可以得到结论,trimToSize中的那行代码得到的就是header.next对应的节点,也就是最近最不常使用的那个节点。

 以上就是Java和Android的LRU缓存及实现原理 的内容,更多相关内容请关注PHP中文网(www.php.cn)!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!