Junior — Middle
How is the lifetime of an object determined in this cache?
sobes.tech AI
Answer from AI
The lifetime of an object in cache is usually determined by cache management policies, which may include:
- Time To Live (TTL): the object is stored in cache for a specified duration from the moment it is added.
- Idle Time: the object is removed if it has not been accessed for a certain period.
- Maximum cache size: when the size exceeds a limit, old objects are removed according to a specific strategy (e.g., LRU — Least Recently Used).
For example, if the cache has a TTL of 10 minutes, then after 10 minutes from the addition, the object is automatically considered stale and is removed or updated upon the next request.
In Java cache (e.g., Guava Cache), this can be configured as follows:
Cache<String, Object> cache = CacheBuilder.newBuilder()
.expireAfterWrite(10, TimeUnit.MINUTES)
.build();
Here, the object will live in the cache for 10 minutes after being written.