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.

Code

LastInFirstOut
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.

LIFOTest

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.

Code

The code is available on my GitHub.

Next

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

References

[1] https://github.com/luizgustavocosta/luiz-costa-tech/tree/master/cache-eviction-policies

[2]https://luizcostatech.medium.com/cache-eviction-policy-in-java-part-1-of-5-9acb65c252ec

Hi there 👋 , I’m Luiz Gustavo I’m a Brazilian and don’t play soccer very well, then I became a software developer