java
You are tasked with designing a thread-safe in-memory cache system in Java.
The cache must satisfy the following requirements:
Eviction Policy: Least Recently Used (LRU).
Thread Safety: Multiple threads must be able to read and write concurrently without corrupting the cache state.
Maximum Size: The cache must hold at most N elements. When the limit is exceeded, it should evict the least recently accessed element.
Performance Constraint: Both get(key) and put(key, value) operations must run in O(1) time complexity.
Tasks:
Describe which Java data structures you would use to implement this and why.
Implement the core get and put methods.
Explain how you would ensure thread-safety without introducing major performance bottlenecks (hint: locking strategies).
Extend your cache so that it can optionally expire entries after a certain timeout duration, even if they are not accessed (think time-to-live per entry).
Bonus Challenge:
Can you optimize it even further by reducing global locks, allowing even better concurrency using finer-grained locks or Java's ConcurrentHashMap?
Posted By: admin
Solution