博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
A LRU Cache in 10 Lines of Java
阅读量:6328 次
发布时间:2019-06-22

本文共 2210 字,大约阅读时间需要 7 分钟。

hot3.png

I had a couple of interviews long ago which asked me to implemented a  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 ). 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 ().

Without further ado:

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

转载于:https://my.oschina.net/u/553266/blog/479096

你可能感兴趣的文章
CentOS下关闭Sendmail服务的方法
查看>>
html select 标签知多少
查看>>
adb操作手机打电话、发短信
查看>>
Shell学习笔记---date_pratice.sh
查看>>
Maven入门(含实例教程)
查看>>
LinkedList的用法小结
查看>>
防xss攻击,需要对请求参数进行escape吗?
查看>>
字符串匹配算法之SimHash算法
查看>>
嵌入式linux------SDL移植(am335x下显示bmp图片)
查看>>
程序员,一个吃青春饭的行业
查看>>
GMap.Net开发之技巧小结
查看>>
Android--绑定服务调用服务的方法
查看>>
Eclipse中ClassPath问题
查看>>
Greenplum行存与列存的选择以及转换方法
查看>>
iOS开发之窥探UICollectionViewController(三) --使用UICollectionView自定义瀑布流
查看>>
Java开发中程序和代码性能优化
查看>>
Studying...
查看>>
符号化你的iOS崩溃报告
查看>>
【原创】.NET平台机器学习组件-Infer.NET连载(一)介绍
查看>>
用户画像数据建模方法
查看>>