LRU Cache Implementation in Java

筅森魡賤 提交于 2019-12-05 06:40:22

the point here is, i guess, that you need to check if the LRU is at it's maximum size. the check here is NOT (map.size() > maxSize), it is ">=". now, you could probably replace that with "if (map.size() == maxSize) {...}" - which, in ideal conditions, should do exactly the same thing.

but in not-so-ideal conditions, if for whatever reason, somebody put an EXTRA entry in the map without checking, then with this code, the map would NEVER go down in size again, because the if condition would never be true.

so - why not "while" and ">=" instead of "if" and "=="? same amount of code, plus more robust against "unexpected" conditions.

An easy implementation of an LRU cache does the following, a while loop is only need when the max size is adjusted, but not for the primitive operations:

  • During put, remove superflous element.
  • During get, move element to top.

The primitive operations will be one shot. You can then use either ordinary synchronized or read write lock around this data structure.

When using read write locks the fairness on who comes first is then rather an issue of the used read write locks than of the LRU cache itself.

Here is a sample implementation.

It's not wrong but just a safety in case of accidental modification. You could check for equality with concurrentLinkedQueue.size() == maxSize in a conditional statement.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!