TimedCache

Introduction

Timed cache defines an expiration time for cached objects, and objects that exceed the expiration time will be cleaned up. This cache has no capacity limit, and objects will only be removed after they expire.

Usage

// Create a cache with a default expiration time of 4 milliseconds
TimedCache<String, String> timedCache = CacheUtil.newTimedCache(4);
// Create an instance
// TimedCache<String, String> timedCache = new TimedCache<String, String>(4);

timedCache.put("key1", "value1", 1); // Expires after 1 millisecond
timedCache.put("key2", "value2", DateUnit.SECOND.getMillis() * 5);
timedCache.put("key3", "value3"); // Default expiration (4 milliseconds)

// Start a scheduled task to clean up expired entries every 5 milliseconds. Uncomment this line to start cleaning up expired entries for the first time.
timedCache.schedulePrune(5);

// Wait for 5 milliseconds
ThreadUtil.sleep(5);

// After 5 milliseconds, only value2 is retained because it is set to expire after 5 milliseconds
String value1 = timedCache.get("key1"); // null
String value2 = timedCache.get("key2"); // value2

// After 5 milliseconds, the default expiration time is set, so key3 is only retained for 4 milliseconds and is therefore null
String value3 = timedCache.get("key3"); // null

// Cancel the scheduled cleanup
timedCache.cancelPruneSchedule();

If the user calls the get(key) method before the timeout, the starting time will be recalculated. For example, if the user sets the timeout time of key1 to 5s, and the user calls the get("key1") method at 4s, the timeout time will be recalculated, and calling the get("key1") method again after another 4s will still return the value. To avoid this mechanism, call the get("key1", false) method instead.

Note: If the timer is started, it will periodically clean up expired values in the cache, but if it is not started, it will only check for expiration and clean up when getting the value. The problem with not starting the timer is that some values will occupy cache space if they are not accessed for a long time.