A LRU Cache in 10 Lines of Java

來源:互聯網
上載者:User

標籤:

I had a couple of interviews long ago which asked me to implemented a least recently used (LRU) cache. A cache itself can simply be implemented using a hash table, however adding a size limit gives an interesting twist on the question. Let’s take a look at how we can do this.

Least Recently Used Cache Eviction

To accomplish cache eviction we need to be easily able to:

  • query the last recently used item

  • mark an item as the most recently used item

A linked list allows for both operations. Checking for the least recently used item can just return the tail. Marking an item as recently used can be simply removing it from its current position and moving it to the head. The missing puzzle piece is finding this item in the linked list quickly.

Hash tables to the rescue

Looking into our data structure toolbox, hash tables allow us to easily index an object in (amortized) constant time. If we create a hash table from key -> list node, we can find the most recently used node in constant time. The converse is true in that we can also still check for the existence (or lack-there-of) in constant time as well.

After looking up the node we can then move it to the front of the linked list to mark it as the most recently used item.

The Java shortcut

Sometimes knowing less common data structures from the standard library of various programming languages can prove to be of help. Given this hybrid data structure we would have to implement a hash table on top of a linked list. However Java already provides this for us in the form of a LinkedHashMap! It even provides an overridable eviction policy method (removeEldestEntry docs). The only catch is that by default the linked list order is the insertion order, not access. However one of the constructor exposes an option use the access order instead (docs).

Without further ado:

import java.util.LinkedHashMap;import java.util.Map; public class LRUCache<K, V> extends LinkedHashMap<K, V> {  private int cacheSize;   public LRUCache(int cacheSize) {    super(16,  0.75f, true);    this.cacheSize = cacheSize;  }   protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {    return size() >= cacheSize;  }}


A LRU Cache in 10 Lines of Java

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.