FIFOCache

Introduction

FIFO (first in first out) strategy. Elements are continuously added to the cache until it is full. When the cache is full, expired cache objects are cleaned up. If the cache is still full after cleanup, the first-in cache object (the object at the head of the linked list) is deleted.

Advantages: Simple and fast Disadvantages: Inflexible, cannot guarantee that the most commonly used objects are always retained

Usage

Cache<String, String> fifoCache = CacheUtil.newFIFOCache(3);

// Add elements, each element can set its expiration time, DateUnit.SECOND.getMillis() represents the number of milliseconds per second, here it is 3 seconds
fifoCache.put("key1", "value1", DateUnit.SECOND.getMillis() * 3);
fifoCache.put("key2", "value2", DateUnit.SECOND.getMillis() * 3);
fifoCache.put("key3", "value3", DateUnit.SECOND.getMillis() * 3);

// Since the cache capacity is only 3, when adding the fourth element, the first object placed will be removed according to the FIFO rule
fifoCache.put("key4", "value4", DateUnit.SECOND.getMillis() * 3);

// value1 is null
String value1 = fifoCache.get("key1");