Cache eviction policy in Java — Part 2 of 5 — LIFO

Hi I’m Luiz Costa, you might remember me from Cache eviction policy in Java — Part 1 of 5 [Troy Mcclure quotes] 😄.

Cache eviction policy in Java — LIFO

Where could I use this kind of cache?

This kind of cache can be used in: Movies 🎥, accounting, baggage 🏪, delivery items 🛵, trolley shopping cart 🛒, parking lot 🚙, even for dish wash 🍽 and so on


The list must store at a maximum of 3 elements and the cache starts always with 3 players, Coutinho, Neto, and Messi all FCB’s ⚽️ players.


The LIFO (Last In First Out) is a data structure where the last element added is the first to be removed.

In this tutorial will be used a LinkedHashSet to store the elements and a variable to point to the last element added, to make the delete easier.

However Java handles it for you, the class public class Stack<E> extends Vector<E> works as the name says LIFO but no using Key and Value.

Below is the class that works as a LIFO eviction policy. Pay attention to method put. This method is responsible to add a new element and remove the newer.


Last In First Out table

On the left is the behaviour of LIFO where the list is built using Coutinho, Neto and Messi, added in this order. Being Messi the last will be the first to leave the list.

In sequence when Ronaldinho (#1 — Add) is added Messi is removed and after Andre ter Stegen (#2 — Add) is added and Ronaldinho is removed.


In this scenario the test doesn’t matter how many times the element was accessed before, the last element will be removed.

On the next article will show how to work with Cache and counting the access and decide when an item should be removed based on how many times was accessed.


The code is available on my GitHub.


The next subject will be LFU (Least Frequently Used).






Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Luiz Gustavo De O. Costa

Hey friend!! I’m Luiz Gustavo, a Java developer and I’m here to learn and write about Java, tests and good practices