Thread-Safe LRU Cache with TTL
Implement an in-memory LRUCache class in Ruby. It must support O(1) get and put operations. You need to handle production realities:
Requirements:
get(key)→ Returns value ornilif key doesn't exist or is expired.put(key, value, ttl_seconds)→ Inserts/updates. Evicts least recently used if capacity exceeded. TTL is per-key expiration.- Thread-safe: Multiple threads can safely call
get/putconcurrently. - Expiration happens lazily (on access) or proactively (bonus points).
Example:
cache = LRUCache.new(2) # capacity 2
cache.put("user_1", {name: "Duy"}, 1) # 1 second TTL
sleep(2)
cache.get("user_1") # => nil (expired)