Home > Uncategorized > Simple LRU or FIFO Cache

Simple LRU or FIFO Cache

There is a very simple way to make a FIFO or LRU cache with the existing LinkedHashMap implementation of the default Java VM made by Joshua Bloch.

The LinkedHashMap already has a method you can override, which defines when to remove the “oldest” entry. With the default constructor this is already a FIFO cache, because it is internal sorted after the insertion order.

To Change to LRU cache you have to change the order of the LinkedHashMap to use the access order. You do this with the other constructor new LinkedHashMap(MAX, 0.75, true). ’0.75′ is the default value taken from the LinkedHashMap code itself.

The serialVersionUID is only a proposal of FindBugs, because it is a anonymous inner class now with a changed behavior.

    private static final int MAX = 50;

    private final Map cache = Collections.synchronizedMap(
            new LinkedHashMap(MAX) {

                /** Serial UID. */
                private static final long serialVersionUID = 2546245625L;

                @Override
                protected boolean removeEldestEntry(Map.Entry eldest) {
                    return size() > MAX;
                }
            });

Advertisement
Categories: Uncategorized Tags: , , , ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.